单击按钮更改setTimeout的延迟 [英] Change delay in setTimeout using a button click

查看:125
本文介绍了单击按钮更改setTimeout的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用HTML画布创建3D旋转立方体.我的代码看起来像这样

I am working on creating a 3D rotating cube in HTML canvas. My code looks something like this

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函数更新dacc的值,但这不起作用.还是有其他方法可以调用上面的函数来解决这个问题?

Here dacc is a de-acceleration factor which slows down the rotation. I need to create button friction which will further slow down the de-acceleration by factor x. How do I change the de-acceleration factor while setTimeout is still in progress? I tried updating the value of dacc with an onclick function but that doesn't work. Or is there any other way to call the above function that can help in this ?

感谢您的帮助.

推荐答案

请勿使用计时器更改速度.设备的显示速率固定为每秒60帧.您应该与此速率同步制作动画.使用 requestAnimationFrame (rAF)

Do not use timers to change speed. The display rate of the device is fixed at 60 frames a second. You should animate in sync with this rate. Use requestAnimationFrame (rAF)

下面的代码每60秒使用rAF更新一次动画.

The code below uses rAF to update the animation once ever 60th second.

  • rotateSpeed是每帧旋转多少
  • 每帧此速度降低dacc中的量.如果低于minSpeed分钟,旋转停止;
  • 点击事件可以通过更改dacc
  • 来更改减速率
  • 当转速低于minSpeed时,rAF将停止.
  • 开始动画调用startRotateAnim();
  • rotateSpeed is how much to rotate each frame
  • Each frame this speed is reduced by the amount in dacc. If below some min minSpeed the rotation is stopped;
  • A click event can change the rate of deceleration by changing dacc
  • rAF will stop when the rotate speed is below minSpeed.
  • To start the animation call startRotateAnim();

所使用的值只是您的代码中的一个估计值.您将必须使用这些值来使动画看起来像您想要的样子.

The values used are just an estimate of from your code. You will have to play with the values to get the animation to look how you want.

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的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆