在类中使用requestAnimationFrame

Tc_*_*Tc_ 6 requestanimationframe typescript

我在查找如何requestAnimationFrame在课堂上使用时遇到问题.

这段代码工作正常:

window.onload = function () {
    var width = 20;
    function animation() {
        width++;
        var element = document.getElementById("box");
        element.style.width = width + "px";
        requestAnimationFrame(animation);
    }
    requestAnimationFrame(animation);
};
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将它放入课堂时,我没有得到任何结果.

class Animation{
    width: number = 20;

    constructor() {
        requestAnimationFrame(this.loop);
    }
    loop() {
        this.width++;
        var element = document.getElementById("box");
        element.style.width = this.width + "px";
        requestAnimationFrame(this.loop);
    }
}
window.onload = function () {
    var animation = new Animation();
};
Run Code Online (Sandbox Code Playgroud)

有人能告诉我这里有什么问题吗?

bas*_*rat 11

requestAnimationFrame(this.loop);如果你要传递给别人一个他们要打电话的功能,请使用箭头即requestAnimationFrame(()=>this.loop());loop = () => {

更多:https://www.youtube.com/watch?v = tvocUcbCupA

  • 不要忘记时间参数 requestAnimationFrame((t)=>this.loop(t));<br/> (2认同)