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
Daniel Springer
7,600 Pointshelp running js animation for canvas element
Hey everyone, ive been trying to learn how to do animations on an html canvas element through js, but ive run into a bit of trouble and was wondering if one of you fine gents could help explain to me where ive gone wrong. All i am trying to do is create a simple rectangle object and move it across the screen.
var canvas=document.getElementById('canvas'); var ctx=canvas.getContext("2d"); var width=canvas.width; var height=canvas.height;
var square = { x: 10, y: 10, vx: 5, wh: 25, color:'blue', draw: function(){ ctx.fillRect(this.x,this.y,this.wh,this.wh); ctx.fillStyle=color;}
};
function draw(){ ctx.clearRect(0,0,width,height); square.draw(); ctx.save(); square.x += square.vx; window.requestAnimationFrame(draw);
}
window.onload=draw;
ok so theres the js and from what i understand about what i am trying to accomplish here, i have created a var named square and filled it with information regarding its behaviors and state, i than created the draw function i was wanting to use to animate the square and have it update the x location of the square each time it runs. i also specified at the end of the draw function to create another frame which according to my logic should have a new x location. For some reason the initial image of the square shows but the the animation doesnt seem to run. I dont know if Ive missed something crucial here, but im totally lost. Any help would be appreciated guys.
1 Answer
Clayton Perszyk
Treehouse Moderator 49,057 PointsYou are missing a reference to this here:
ctx.fillStyle=color;
It should be:
ctx.fillStyle=this.color;
Daniel Springer
7,600 PointsDaniel Springer
7,600 Pointsnvmnd ended up checking the console and found i forgot to mark color ---> this.color. srry guys! XD