作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 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.width
,if
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/
我是一名优秀的程序员,十分优秀!