gpt4 book ai didi

javascript - 请求动画帧问题

转载 作者:行者123 更新时间:2023-11-30 00:25:20 25 4
gpt4 key购买 nike

我一直在用 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 沿对 Angular 线向下移动,然后我得到完全绘制的 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

关于javascript - 请求动画帧问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com