我试图理解 Eloquent Javascript: The Document Object Model (Chapter 13) 中这个小代码示例中发生的所有事情。 ,但我不清楚在函数本身传递到 requestAnimationFrame() 之前,“时间”的值到底在哪里传递到 animate() 函数。我到底错过了什么?
<p style="text-align: center">
<img src="img/cat.png" style="position: relative">
</p>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
function animate(time) {
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
最佳答案
当你执行这行:requestAnimationFrame(animate);
时,函数animate
将在requestAnimationFrame
内部被调用,并获得time
变量作为参数传递。像这样的东西(狭窄且粗糙):
function requestAnimationFrame(callback) {
var time = getTime();
callback(time); //Where callback is your `animate` function
};
当然,requestAnimationFrame
看起来与上面的函数完全不同,但这只是为了说明时间
从何而来。
根据文档:
The callback method is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame begin to fire. Multiple callbacks in a single frame, therefore, each receive the same timestamp even though time has passed during the computation of every previous callback's workload. This timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 µs).
在此处了解更多信息:https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
关于javascript - Eloquent JavaScript : DOM Animation snippet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851084/