gpt4 book ai didi

javascript - While 循环与 requestAnimationFrame

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

我正在尝试使用 JavaScript 在 HTML5 Canvas 上绘制时间线。我从 while 循环 开始,但它似乎在 requestAnimationFrame 函数中出现故障。

if 语句工作正常,但我想知道为什么 while 循环和 requestAnimationFrame 函数不能一起工作。

此代码有效

var x = 50
function animate(){
requestAnimationFrame(animate);
c.beginPath();
c.moveTo(50, halfway_y)
c.lineTo(x, halfway_y)
c.strokeStyle = "white"
c.lineWidth = 5;
c.stroke();
if(x < canvas.width - 50){
x+=7
}

}

animate()

此代码不起作用。代码只是画线,没有动画。

var x = 50
function animate(){
requestAnimationFrame(animate);
c.beginPath();
c.moveTo(50, halfway_y)
c.lineTo(x, halfway_y)
c.strokeStyle = "white"
c.lineWidth = 5;
c.stroke();

while(x < canvas.width){
x+=7
}


}

animate()

最佳答案

 while(x < canvas.width) {
x+=7
}

 if(x < canvas.width - 50) {
x+=7
}

这两个代码块是不同的,while block 让x一次到canvas.widthif block 让 x 只增加 7

x = 0
while(x < canvas.width){
x+=7
}
console.log(x);// x = 999

x = 0
if(x < canvas.width - 50){
x+=7
}
console.log(x); // x = 7

关于javascript - While 循环与 requestAnimationFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662251/

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