requestAnimationFrame が setInterval や setTimeout よりも優れているのはなぜですか? 質問する

requestAnimationFrame が setInterval や setTimeout よりも優れているのはなぜですか? 質問する

setTimeout や setInterval ではなく requestAnimationFrame を使用する必要があるのはなぜですか?

この自己回答形式の質問はドキュメントの例です。

ベストアンサー1

高品質のアニメーション。

requestAnimationFramesetTimeoutまたは の使用時に発生するちらつきやずれを完全に排除し、setIntervalフレームのスキップを削減または完全に除去して、より高品質のアニメーションを生成します。

剪断

ディスプレイスキャンの途中で新しいキャンバス バッファーがディスプレイ バッファーに提示され、アニメーションの位置が一致しないためにせん断線が発生する場合です。

ちらつき

これは、キャンバスが完全にレンダリングされる前にキャンバス バッファーがディスプレイ バッファーに提示された場合に発生します。

フレームスキップ

これは、レンダリング フレーム間の時間がディスプレイ ハードウェアと正確に同期していない場合に発生します。一定数のフレームごとにフレームがスキップされ、一貫性のないアニメーションが生成されます。(これを減らす方法はありますが、個人的にはこれらの方法は全体的な結果が悪くなると思います) ほとんどのデバイスは 1 秒あたり 60 フレーム (またはその倍数) を使用するため、16.666...ms ごとに新しいフレームが生成され、タイマーは整数値を使用するsetTimeoutため、setIntervalフレームレートに完全に一致することはできません (17ms に切り上げますinterval = 1000/60)


デモは千の言葉に値します。

アップデート質問に対する答えrequestAnimationFrame ループの fps が正しくありませんsetTimeout のフレーム時間がどのように矛盾しているかを示し、それを requestAnimationFrame と比較します。

デモでは、単純なアニメーション(画面上を移動するストライプ)が表示され、マウス ボタンをクリックすると、使用されるレンダリング更新方法が切り替わります。

更新方法はいくつかあります。アニメーションアーティファクトの正確な外観は、使用しているハードウェアの設定によって異なります。ストライプの動きの小さな動きを探します。

注意: ディスプレイ同期がオフになっているか、ハードウェアアクセラレーションがオフになっている可能性があります。これはすべてのタイミング方法の品質に影響します。低スペックのデバイスではアニメーションに問題が発生することもあります。

  • タイマーアニメーションにはsetTimeoutを使用します。時間は1000/60です

  • RAF最高品質、requestAnimationFrameを使用してアニメーション化します

  • デュアルタイマー2 つのタイマーを使用します。1 つは 1000/60 クリアごとに呼び出され、もう 1 つはレンダリング用に呼び出されます。

    2019年10月更新タイマーがコンテンツを表示する方法にいくつか変更がありました。setIntervalディスプレイの更新と正しく同期しないことを示すために、デュアル タイマーの例を変更し、複数のタイマーを使用すると依然として深刻なちらつきが発生する可能性があることを示しましたsetInterval。これにより発生するちらつきの程度は、ハードウェアの設定によって異なります。

  • タイミングアニメーション付き RAFrequestAnimationFrame を使用しますが、フレーム経過時間を使用してアニメーション化します。この手法はアニメーションでは非常に一般的です。欠陥があると思いますが、それは視聴者に任せます。

  • 時間指定アニメーション付きタイマー. 「時間指定アニメーション付きRAF」として、この場合は「タイマー」方式で見られるフレームスキップを克服するために使用されます。これもまたひどいと思いますが、ゲームコミュニティはディスプレイのリフレッシュにアクセスできない場合に使用する最良の方法であると断言しています。

/** SimpleFullCanvasMouse.js begin **/

var backBuff;
var bctx;
const STRIPE_WIDTH = 250;
var textWidth;
const helpText = "Click mouse to change render update method.";
var onResize = function(){
    if(backBuff === undefined){
        backBuff = document.createElement("canvas")    ;
        bctx = backBuff.getContext("2d");
        
    }
    
    backBuff.width = canvas.width;
    backBuff.height = canvas.height;
    bctx.fillStyle = "White"
    bctx.fillRect(0,0,w,h);
    bctx.fillStyle = "Black";
    for(var i = 0;  i < w; i += STRIPE_WIDTH){
        bctx.fillRect(i,0,STRIPE_WIDTH/2,h)   ;
        
    }
    ctx.font = "20px arial";
    ctx.textAlign = "center";
    ctx.font = "20px arial";
    textWidth = ctx.measureText(helpText).width;
    
};
var tick = 0;
var displayMethod = 0;
var methods = "Timer,RAF Best Quality,Dual Timers,RAF with timed animation,Timer with timed animation".split(",");
var dualTimersActive = false;
var hdl1, hdl2

function display(timeAdvance){  // put code in here

    tick += timeAdvance;
    tick %= w;


    ctx.drawImage(backBuff,tick-w,0);
    ctx.drawImage(backBuff,tick,0);
    if(textWidth !== undefined){
        ctx.fillStyle = "rgba(255,255,255,0.7)";
        ctx.fillRect(w /2 - textWidth/2, 0,textWidth,40);
        ctx.fillStyle = "black";
        ctx.fillText(helpText,w/2, 14);
        ctx.fillText("Display method : " + methods[displayMethod],w/2, 34);
    }
    if(mouse.buttonRaw&1){
        displayMethod += 1;
        displayMethod %= methods.length;
        mouse.buttonRaw = 0;
        lastTime = null;
        tick = 0;
        if(dualTimersActive) {
             dualTimersActive = false;
             clearInterval(hdl1);
             clearInterval(hdl2);
             updateMethods[displayMethod]()             
        }
    }
}








//==================================================================================================
// The following code is support code that provides me with a standard interface to various forums.
// It provides a mouse interface, a full screen canvas, and some global often used variable 
// like canvas, ctx, mouse, w, h (width and height), globalTime
// This code is not intended to be part of the answer unless specified and has been formated to reduce
// display size. It should not be used as an example of how to write a canvas interface.
// By Blindman67
const U = undefined;const RESIZE_DEBOUNCE_TIME = 100;
var w,h,cw,ch,canvas,ctx,mouse,createCanvas,resizeCanvas,setGlobals,globalTime=0,resizeCount = 0; 
var L = typeof log === "function" ? log : function(d){ console.log(d); }
createCanvas = function () { var c,cs; cs = (c = document.createElement("canvas")).style; cs.position = "absolute"; cs.top = cs.left = "0px"; cs.zIndex = 1000; document.body.appendChild(c); return c;}
resizeCanvas = function () {
    if (canvas === U) { canvas = createCanvas(); } canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx = canvas.getContext("2d"); 
    if (typeof setGlobals === "function") { setGlobals(); } if (typeof onResize === "function"){ resizeCount += 1; setTimeout(debounceResize,RESIZE_DEBOUNCE_TIME);}
}
function debounceResize(){ resizeCount -= 1; if(resizeCount <= 0){ onResize();}}
setGlobals = function(){ cw = (w = canvas.width) / 2; ch = (h = canvas.height) / 2; mouse.updateBounds(); }
mouse = (function(){
    function preventDefault(e) { e.preventDefault(); }
    var mouse = {
        x : 0, y : 0, w : 0, alt : false, shift : false, ctrl : false, buttonRaw : 0, over : false, bm : [1, 2, 4, 6, 5, 3], 
        active : false,bounds : null, crashRecover : null, mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")
    };
    var m = mouse;
    function mouseMove(e) {
        var t = e.type;
        m.x = e.clientX - m.bounds.left; m.y = e.clientY - m.bounds.top;
        m.alt = e.altKey; m.shift = e.shiftKey; m.ctrl = e.ctrlKey;
        if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1]; }  
        else if (t === "mouseup") { m.buttonRaw &= m.bm[e.which + 2]; }
        else if (t === "mouseout") { m.buttonRaw = 0; m.over = false; }
        else if (t === "mouseover") { m.over = true; }
        else if (t === "mousewheel") { m.w = e.wheelDelta; }
        else if (t === "DOMMouseScroll") { m.w = -e.detail; }
        if (m.callbacks) { m.callbacks.forEach(c => c(e)); }
        if((m.buttonRaw & 2) && m.crashRecover !== null){ if(typeof m.crashRecover === "function"){ setTimeout(m.crashRecover,0);}}        
        e.preventDefault();
    }
    m.updateBounds = function(){
        if(m.active){
            m.bounds = m.element.getBoundingClientRect();
        }
        
    }
    m.addCallback = function (callback) {
        if (typeof callback === "function") {
            if (m.callbacks === U) { m.callbacks = [callback]; }
            else { m.callbacks.push(callback); }
        } else { throw new TypeError("mouse.addCallback argument must be a function"); }
    }
    m.start = function (element, blockContextMenu) {
        if (m.element !== U) { m.removeMouse(); }        
        m.element = element === U ? document : element;
        m.blockContextMenu = blockContextMenu === U ? false : blockContextMenu;
        m.mouseEvents.forEach( n => { m.element.addEventListener(n, mouseMove); } );
        if (m.blockContextMenu === true) { m.element.addEventListener("contextmenu", preventDefault, false); }
        m.active = true;
        m.updateBounds();
    }
    m.remove = function () {
        if (m.element !== U) {
            m.mouseEvents.forEach(n => { m.element.removeEventListener(n, mouseMove); } );
            if (m.contextMenuBlocked === true) { m.element.removeEventListener("contextmenu", preventDefault);}
            m.element = m.callbacks = m.contextMenuBlocked = U;
            m.active = false;
        }
    }
    return mouse;
})();


resizeCanvas(); 
mouse.start(canvas,true); 
onResize()
var lastTime = null;
window.addEventListener("resize",resizeCanvas); 
function clearCTX(){
    ctx.setTransform(1,0,0,1,0,0); // reset transform
    ctx.globalAlpha = 1;           // reset alpha
    ctx.clearRect(0,0,w,h); // though not needed this is here to be fair across methods and demonstrat flicker
}



function dualUpdate(){
    if(!dualTimersActive) {
        dualTimersActive = true;
        hdl1 = setInterval( clearCTX, 1000/60);
        hdl2 = setInterval(() => display(10), 1000/60);
    }
}
function timerUpdate(){
    timer = performance.now();
    if(!lastTime){
        lastTime = timer;
    }
    var time = (timer-lastTime) / (1000/60);
    lastTime = timer;    
    setTimeout(updateMethods[displayMethod],1000/60);
    clearCTX();
    display(10*time);
}
function updateRAF(){ 
    clearCTX();
    requestAnimationFrame(updateMethods[displayMethod]);
    display(10);  
}
function updateRAFTimer(timer){ // Main update loop

    clearCTX();
    requestAnimationFrame(updateMethods[displayMethod]);
    if(!timer){
        timer = 0;
    }
    if(!lastTime){
        lastTime = timer;
    }
    var time = (timer-lastTime) / (1000/60);
    display(10 * time);  
    lastTime = timer;
}

displayMethod = 1;
var updateMethods = [timerUpdate,updateRAF,dualUpdate,updateRAFTimer,timerUpdate]
updateMethods[displayMethod]();

/** SimpleFullCanvasMouse.js end **/

おすすめ記事