[英]Change delay in setTimeout using a button click
我正在努力在 HTML canvas 中創建一個 3D 旋轉立方體。 我的代碼看起來像這樣
function rotateCubeZM() {
fr = 5;
stoppage = 1;
for(let i = 0;i<200;i++,fr+=dacc) {
setTimeout(rotateCubeZ,i*fr*stoppage,1);
}
}
這里的 dacc 是一個減慢旋轉的減速因子。 我需要創建按鈕摩擦,這將進一步減慢 x 因子的減速。 如何在 setTimeout 仍在進行時更改減速因子? 我嘗試使用 onclick function 更新 dacc 的值,但這不起作用。 或者有沒有其他方法可以調用上述 function 來幫助解決這個問題?
謝謝您的幫助。
不要使用計時器來改變速度。 該設備的顯示速率固定為每秒 60 幀。 您應該與此速率同步動畫。 使用requestAnimationFrame (rAF)
下面的代碼使用 rAF 每 60 秒更新一次 animation。
rotateSpeed
是每幀旋轉多少dacc
中的數量。 如果低於某個 min minSpeed
則停止旋轉;dacc
來改變減速率startRotateAnim();
使用的值只是您的代碼的估計值。 您將不得不使用這些值來讓 animation 看起來像您想要的那樣。
const fr = 5;
const minSpeed = 0.01;
var rotateSpeed = 0, dacc;
// click event for quicker slowdown
myButtonElement.addEventListener("click",() => dacc = 0.8);
// function to start / restart animation
function startRotateAnim() {
const animRunning = rotateSpeed > minSpeed; // if animation running just change values
rotateSpeed = 1 * (1000/60) / fr; // rotate per frame
dacc = 0.4; // the bigger the number the quicker the slowdown
if (!animRunning) {
requestAnimationFrame(mainLoop); // start the animation.
}
}
function mainLoop() { // this is called 60 times a second
if (rotateSpeed > minSpeed) { rotateSpeed -= dacc }
if (rotateSpeed > minSpeed) {
rotateCubeZ(rotateSpeed);
requestAnimationFrame(mainLoop);
}
}
你不能那樣做。 您必須清除超時並設置新的超時。 setTimeout
返回一個唯一標識符。
// timer holds the timer identifier.
let timer = setTimeout(function, 1000);
// clear it when you click the button
clearTimeout(timer);
// and set new timer with new value
timer = setTimeout(function, 2000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.