【问题标题】:Why is cancelAnimationFrame not working?为什么 cancelAnimationFrame 不起作用?
【发布时间】:2015-07-29 04:51:08
【问题描述】:

参考这个小提琴 - http://jsfiddle.net/rnqLfz14/28/

[此代码不是我的-http://www.isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing]

//....

function stop() {
    running = false;
    started = false;
    cancelAnimationFrame(frameID);
}

//...

function mainLoop(timestamp) {
    // Throttle the frame rate.
    if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
        frameID = requestAnimationFrame(mainLoop);
        return;
    }
    delta += timestamp - lastFrameTimeMs;
    lastFrameTimeMs = timestamp;

    begin(timestamp, delta);

    if (timestamp > lastFpsUpdate + 1000) {
        fps = 0.25 * framesThisSecond + 0.75 * fps;

        lastFpsUpdate = timestamp;
        framesThisSecond = 0;
    }
    framesThisSecond++;

    var numUpdateSteps = 0;
    while (delta >= timestep) {
        update(timestep);
        delta -= timestep;
        if (++numUpdateSteps >= 240) {
            panic();
            break;
        }
    }

    draw(delta / timestep);

    T.textContent = timestamp;

    if (timestamp >= 6000.0) {
        T.textContent = "Stopped!";
        stop();
    }

    end(fps);

    frameID = requestAnimationFrame(mainLoop);
}
//...

cancelAnimationFrame 函数不会停止动画循环。有什么建议吗?我已经为它挠了很长时间了,如果有任何建议,我将不胜感激。

【问题讨论】:

  • 看起来您无论如何都会在mainLoop 末尾调用requestAnimationFrame(mainLoop);
  • 是的......我的坏......代码创建者也没有想到这一点?
  • 我也差点炸了脑袋。答案很准确!

标签: javascript html animation requestanimationframe


【解决方案1】:

当满足stop() 的条件时,会调用stop(),但代码会继续,因此将请求新的 rAF。

只需在 stop 调用后添加一个 return 即可防止这种情况发生(或使用 else):

...
if (timestamp >= 6000.0) {
    T.textContent = "Stopped!";
    stop();  // stop() is just a sub-routine here and will continue after being called
    return;  // <--- here
}
...

Modified fiddle

【讨论】:

  • 谢谢!您还可以建议此代码背后的基本框架是否适合创建游戏?我的代码至少是基于这个原理的。
猜你喜欢
  • 2019-02-22
  • 2013-07-04
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
相关资源
最近更新 更多