重新审视我的一个旧实验。我正在使用间隔来旋转元素。现在我想将间隔改为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); */
};
}
答案 0 :(得分:1)
您可以使用this
方法
bind()
的值
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/