Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

trying to draw ball on canvas with js using objects?

I've been trying to draw a ball using JS objects and function on a canvas? its not showing anywhere on the canvas, not sure what im doing wrong or problem not asking google the right question..

const ruleBtn = document.querySelector('.rules-btn');
const closeBtn = document.querySelector('.close-btn');
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const showRules = document.querySelector('.rules');

//create ball
const ball = {
    w: canvas.width / 2,
    y: canvas.height / 2,
    size: 10,
    speed: 5,
    dx: 4,
    dy: -4,
    visible: true
};

//draw ball function
function drawBall(){
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.size, 0, Math.PI*2);
    ctx.fillStyle = "#00000";
    ctx.fill();
    ctx.closePath();
}

****NOTE: this is not all the code just part of it. will post rest if you need it. thanks guys an gals!

2 Answers

In the drawBall function you reference ball.x, but the ball object doesn’t have an x property. I think you meant for the w property in the ball object to be named x.

Think that may have something to do with your ball not showing up.

Thanks man! I have a bad habit of typos biggest thing that kills me lol I appreciate it!

Quick scan of your code. Your hex value for ctx.fillStyle is only 5 characters. I’m sure you have bigger things to address, but I would suggest fixing that first :-)