0

After the requestAnimationFrame is called, the square does not move. The square is expected to move though.

What is wrong with this code?

http://jsfiddle.net/o3qbesy6/1/

    // Check if canvas exists and get the context of the canvas
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');

// Add width and height of the canvas
var width = 640, height = 480;

// Make the canvas width and height as the variables
canvas.width = width, canvas.height = height;

rect = {
    x: 0,
    y: 0,
    width: 100,
    height: 100
}

ctx.fillStyle = 'red';
ctx.fillRect(rect.x,rect.y,rect.width,rect.height);

function animate(){

    if(rect.x <= 200){
        rect.x += 5;
    }
    requestID = requestAnimationFrame(animate);
}

requestAnimationFrame(animate);
GSquadron
  • 204
  • 3
  • 12
  • 2
    Each frame will have to redraw the canvas, [clearing the previous frame](http://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing) and replacing the rectangle. – Jonathan Lonowski May 04 '15 at 20:10
  • 1
    Ok, this is the solution in case someone gets stuck like me. http://jsfiddle.net/o3qbesy6/2/ – GSquadron May 04 '15 at 20:11
  • You should do it like this: http://jsfiddle.net/o3qbesy6/4/ But i think this is only for testing purposes? – RafaelKr May 04 '15 at 20:14
  • Yeah, first time trying it. Your solution seems better, since I noticed the red square didn't pop up in the first frame in my case. – GSquadron May 04 '15 at 20:31
  • I just tried the example in Internet explorer from my local file and it seems to stutter, meanwhile in jsfiddle, it doesn't. What could the problem be? – GSquadron May 04 '15 at 21:20

0 Answers0