请求动画帧问题

Request Animation Frame issue

我一直在用 RequestAnimationFrame 和 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);
}

问题是我希望 Rect() 与变量 v_x 和 v_y 以及 requestAnimationFrame 沿对角线向下移动,然后我得到完全绘制的 Rectangle,但它没有移动!

因为需要设置矩形的位置为xy而不是0,0。因此,将此 ctx.rect(0,0,50,50) 更改为 ctx.rect(x,y,50,50)。除此之外,您还需要在重绘之前清除 canvas:

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);
}

Fiddle Example