从interval到requestAnimationFrame
From interval to requestAnimationFrame
重温我的一个旧实验。我正在使用间隔来旋转元素。现在我想将间隔更改为 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/
重温我的一个旧实验。我正在使用间隔来旋转元素。现在我想将间隔更改为 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/