我有以下JavaScript:
function animate() {
// call other function
offset += 3;
if (offset > 15) offset = 0;
/// make the animation loop loop
var request = requestAnimationFrame(animate);
}
然后在我的HTML中:
<body onl oad="animate()" >
这一切都很好,它保持动画不断循环,这是伟大的.但我想知道如何使这个动画运行4秒然后停止.
“呼叫其他功能”只是一条向下移动然后重置的线路,给人一种向下移动的印象.这一切都是在Canvas完成的.
任何帮助将非常感激!
解决方法:
您可以使用requestAnimationFrame的参数,该参数是经过的时间(以毫秒为单位) – 这将为您提供非常准确的时间:
function loop(elapsedTime) {
if (elapsedTime >= 4000) return; /// break loop after 4 seconds
requestAnimationFrame(loop); /// provides elapsed time as arg. to loop
}
/// start loop with rAF to get a valid argument first time:
requestAnimationFrame(loop);
The callback method is passed a single argument, a
DOMHighResTimeStamp, which indicates the time, in milliseconds but
with a minimal precision of 10 µs, at which the repaint is scheduled
to occur.