gpt4 book ai didi

javascript - Eloquent Javascript : DOM Animation snippet

转载 作者:行者123 更新时间:2023-11-29 19:25:54 25 4
gpt4 key购买 nike

我试图理解 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 与上面的函数完全不同,但这只是为了说明 time 的来源。

根据文档:

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/

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