Since learning Canvas animation, have said Requestanimationframe good, has been used, also did not feel anything too special place, until just now, after writing the "small ball collision wall----Kill error", Suddenly want to see if this change back to SetInterval, will be what kind of gap, how big?
Results.... A look startled, the gap is too big, say nasty point, setinterval ... It's just like crap.
As a result, you just need to replace the Gamleloop method in the previous article with the one in front of the method Gameloop () to the following code, and you'll know.
function Gameloop () { ctx.clearrect (0,0, canvas_width,canvas_height); Ball.draw (CTX); Ball.update ();} SetInterval (Gameloop,30)
If you do not do your own practice, you cannot make progress, indeed.
Requestanimationframe easy-to-compatible method
Window.requestanimframe = (function() { return window.requestanimationframe | | Window.webkitrequestanimationframe | | Window.mozrequestanimationframe | | Window.orequestanimationframe | | Window.msrequestanimationframe | | function /* */*** element ) {return Window.settimeout (callback, 1000/60); };}) ();
A more complete approach
(function() { varLasttime = 0; varVendors = [' WebKit ', ' Moz ']; for(varx = 0; x < vendors.length &&!window.requestanimationframe; ++x) {window.requestanimationframe= Window[vendors[x] + ' requestanimationframe ']; Window.cancelanimationframe= Window[vendors[x] + ' cancelanimationframe '] | |//The name of this cancellation method in WebKit has changed.Window[vendors[x] + ' cancelrequestanimationframe ']; } if(!window.requestanimationframe) {window.requestanimationframe=function(callback, Element) {varCurrtime =NewDate (). GetTime (); varTimetocall = Math.max (0, 16.7-(Currtime-lasttime)); varid = window.settimeout (function() {Callback (Currtime+Timetocall); }, Timetocall); Lasttime= Currtime +Timetocall; returnID; }; } if(!window.cancelanimationframe) {window.cancelanimationframe=function(ID) {cleartimeout (ID); }; }}());
Requestanimationframe and Setinterval,settimeout