从间隔到请求动画帧

From interval to requestAnimationFrame

本文关键字:动画 请求      更新时间:2023-09-26

重温我的一个旧实验。我正在使用间隔来旋转元素。现在我想将间隔更改为 rAF。我尝试重写了几次Rotation.start方法,但我没有成功。由于我是这个requestAnimationFrame的新手,我不知道还能尝试什么。

相关JS代码:

function Rotation(mass) {
    this.mass       = mass;
    this.angle      = 0;
    this.velocity   = 1;
    this.fps        = 1000/25; // for interval
    this.handler    = null;
    this.rotate     = function () {
                        // when called from rAF "this" refers to window, method fails
                        this.angle  = (this.angle + this.velocity) % 360;
                        var transform   = "rotate(" + this.angle + "deg)";
                        this.mass.elm.style.webkitTransform = transform;
                    };
    this.start      = function () {
                        var rotation = this; // this = Rotation
                        rotation.handler = setInterval(function () {
                            // inside the interval "this" refers to window
                            // that's why we set rotation to "this" at the beginning
                            // so we can access the Rotation obj
                            rotation.rotate();
                        }, rotation.fps);
                        /* requestAnimationFrame(rotation.rotate); */
                    };
}

小提琴(完整代码)

可以使用 bind() 方法绑定this的值

function Rotation(mass) {
    this.mass       = mass;
    this.angle      = 0;
    this.velocity   = 1;
    this.handler    = null;
    this.rotate     = function () {
                        this.angle  = (this.angle + this.velocity) % 360;
                        var transform   = "rotate(" + this.angle + "deg)"
                        this.mass.elm.style.webkitTransform = transform;
                        //call bind on this.rotate so we can properly associate this
                        window.requestAnimationFrame(this.rotate.bind(this));
                    };
    this.start      = function () {
                        //then just start the animation by using this.rotate()
                        this.rotate();
                    };
}

工作 JSFiddle: http://jsfiddle.net/gvr16mcL/