Reputation: 19
I've been writing some examples with RequestAnimationFrame and Canvas:
var ctx;
var x=0,y=0,v_x=5,v_y=5;
window.addEventListener('load',init);
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(f){
window.setTimeout(f,1000/60);
}
})();
function init(){
ctx = document.getElementById("canvas").getContext("2d");
draw();
}
function draw(){
ctx.beginPath();
ctx.rect(0,0,50,50);
ctx.closePath();
ctx.fill();
x += v_x;
y += v_y;
requestAnimationFrame(draw);
}
The problem is that I want the Rect() to go diagonally down with the variables v_x and v_y and the requestAnimationFrame, then I get the Rectangle fully drawn, but it doesn't move!
Upvotes: 2
Views: 95
Reputation: 21575
Because you need to set the position of the rectange to be x
and y
other than 0,0
. So change this ctx.rect(0,0,50,50)
, to this ctx.rect(x,y,50,50)
. Along with that you will want to clear the canvas before you redraw:
function draw(){
ctx.clearRect(0,0,width,height); // Clears the canvas
ctx.beginPath();
ctx.rect(x,y,50,50); // Sets the rects pos to be x,y
ctx.closePath();
ctx.fill();
x += v_x;
y += v_y;
requestAnimationFrame(draw);
}
Upvotes: 1