JavaScript でループ処理を行うための関数のひとつ requestAnimationFrame
。
今さらながら調べ直してみた。
調べなおすきっかけは three.js REVISION: ’63’ のソースを眺めたから。
requestAnimationFrame
ループ処理を行うための他の手段は時間ベースの2つの関数です。
setTimeout, setInterval
今では setTimeout, setInterval は非効率で requestAnimationFrame が実装されているブラウザでは使うべきでは無いと言われています。
IE にも実装され microsoft のサイトで解説を見ることができます。
ie.microsoft.com: requestAnimationFrame API
MSDN: Timing control for script-based animations (“requestAnimationFrame”)
ね、あの○○なmicrosoftでも requestAnimationFrame を使った方が良いって言ってるぐらいですから、使わなくっちゃ。
以前の記事: JavaScript, requestAnimationFrameを下位互換実装するために
Paul IrishさんとErik Möllerさんのコードを記載しています。
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame var lastTime = 0; var vendors = [ 'ms', 'moz', 'webkit', 'o' ]; for( var x = 0, limit = vendors.length; x < limit && !window.requestAnimationFrame; ++x ) { window.requestAnimationFrame = window[ vendors[ x ]+'RequestAnimationFrame' ]; window.cancelAnimationFrame = window[ vendors[ x ]+'CancelAnimationFrame' ] || window[ vendors[ x ]+'CancelRequestAnimationFrame' ]; } if ( !window.requestAnimationFrame ) { window.requestAnimationFrame = function( callback ) { var currTime = new Date().getTime(); var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall ); lastTime = currTime + timeToCall; return id; }; } if ( !window.cancelAnimationFrame ) { window.cancelAnimationFrame = function( id ) { clearTimeout( id ); }; } |
お二人には感謝しかありません。
IE 11 も登場しましたが無難に使えているように思ってました。
思ってたのは three.js のソースを眺めるまででした。
three.jsの実装が少し違ってた
WebGL なライブラリ three.js にも requestAnimationFrame が使われており互換対策が行われています。
ソースコメントにPaul IrishさんとErik Möllerさんへのコメントが見られます。
それぞれのサイトへの上記URLへの記載もあります。
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel |
もうお一人 Tino Zijdelさんは Crisp’s blog の方でしょうか…
もう一行コメントがあります。
// using 'self' instead of 'window' for compatibility with both NodeJS and IE10. |
windowの代わりにselfを使うってことらしいです。
実際にコードは上記コードの window が self に全て置き換えられています。
IE 10 でも window.requestAnimationFrame で使えてたようだけどなぁ。
NodeJS の詳しいこと良くわからない。
selfってなんだ?
self はグローバルオブジェクトらしい。
W3C: self attribute
stackoverflow: Difference between this and self in JavaScript
console.log( window === window.self );// true console.log( this === window.self );// true console.log( this === window );// true console.log( self === window );// true console.log( self === this );// true |
window, this, self, window.self は全て同じということらしい…
self と window も同じもの…
なのにthree.jsはwindowからselfに変えたんや。
何でだろう?
windowとselfはなにが違うの?
結局良くわからなかった。
教えてエロい人。