Javascript requestAnimationFrame,非全局?
所以我尝试创建一个“Animator”模块,它基本上可以轻松启动和停止requestAnimationFrame循环Javascript requestAnimationFrame,非全局?,javascript,html,global-variables,requestanimationframe,Javascript,Html,Global Variables,Requestanimationframe,所以我尝试创建一个“Animator”模块,它基本上可以轻松启动和停止requestAnimationFrame循环 define(function(require, exports, module) { var a = require( 'js/lib/stats.min.js' ); function Animator(){ this.stats = new Stats(); this.stats.domElement.style.position = 'ab
define(function(require, exports, module) {
var a = require( 'js/lib/stats.min.js' );
function Animator(){
this.stats = new Stats();
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.bottom = '0px';
this.stats.domElement.style.right = '0px';
this.stats.domElement.style.zIndex = '999';
this.requestAnimationFrame = requestAnimationFrame;
document.body.appendChild( this.stats.domElement );
}
Animator.prototype.start = function(){
this.animate( this );
}
Animator.prototype.stop = function(){
if (requestId) {
cancelAnimationFrame(this.requestId);
this.requestId = undefined;
}
}
Animator.prototype.animate = function( ){
this.update();
this.requestId = this.requestAnimationFrame( this.animate );
}
// Empty function, because it will be user defined
Animator.prototype.update = function(){
}
return Animator
});
你可以看出我在做一些非法的事情:
首先,我尝试将requestAnimationFrame分配给这个.requestAnimationFrame。这是因为在原型的.animate函数中,我希望能够访问此对象的更新函数。问题是,当我这样做时:
Animator.prototype.animate = function( ){
whichAnimator.update();
whichAnimator.requestId = requestAnimationFrame( whichAnimator.animate( whichAnimator ) );
}
我得到超过最大堆栈调用数
我想我想知道最好的方法是什么,因为在这一点上,我显然不知道我在做什么
如果您有任何问题,请提出,并提前感谢您的时间 .bind做到了
谢谢@kalley
Animator.prototype.start = function(){
this.running = true;
this.animate();
}
Animator.prototype.stop = function(){
this.running = false;
}
Animator.prototype.animate = function( ){
this.stats.update();
this.update();
if( this.running == true ){
window.requestAnimationFrame( this.animate.bind( this ) );
}
}
requestAnimationFrame
不像setInterval
那样工作,每个调用的requestID
都会不同。因此,将其分配给上下文是毫无意义的
我发现,如果您只需全局运行单个requestAnimationFrame
,然后调用循环中运行的任何动画,就更容易喘息。下面是一些粗略的代码:
var animations = {}; // holder for animation functions
(function loop() {
for(var id in animations) {
animations[id]();
}
requestAnimationFrame(loop);
}());
function start(fn) {
var id = +new Date();
animations[id] = fn;
return id;
}
function stop(id) {
if (animations.hasOwnProperty(id)) {
delete animations[id];
}
}
可能想看看如何使用。这将使您能够访问此。完美!直到今天,我才知道bind,但它正是我想要的!