Javascript 请求动画帧问题
我一直在用RequestAnimationFrame和Canvas编写一些示例:Javascript 请求动画帧问题,javascript,canvas,requestanimationframe,Javascript,Canvas,Requestanimationframe,我一直在用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 || wind
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成对角线向下移动,然后完全绘制矩形,但它不移动 因为您需要将矩形范围的位置设置为
x
和y
,而不是0,0
。因此,将这个ctx.rect(0,0,50,50)
更改为这个ctx.rect(x,y,50,50)
。此外,您还需要在重新绘制之前清除画布:
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);
}