troytc
troytc

Reputation: 662

Limiting the framerate of HTML <video> element

Would it be possible, through JS or otherwise, to limit the FPS of a <video> element? I've gotten as far as determining that it probably needs to be drawn to a <canvas>, but then how would one limit the frames drawn per second on that <canvas>?

Upvotes: 2

Views: 1612

Answers (1)

brianchirls
brianchirls

Reputation: 7853

Simple enough. The best way to do any kind of video/canvas effects is to start with requestAnimationFrame, and then on each cycle, you can choose whether to draw the frame or to skip it. Assuming 2D canvas for maximum compatibility, like so:

var MAX_FRAME_RATE = 5, // frames per second
    FRAME_DIFF = 1000 / MAX_FRAME_RATE,
    canvas = document.getElementById('canvas'),
    video = document.getElementById('video'),
    ctx = canvas.getContext('2d'),
    lastDraw = 0;

function render() {
    var now = Date.now(),
        diff = now - lastDraw;

    if (diff >= FRAME_DIFF) {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        lastDraw = now;
    }

    requestAnimationFrame(render);
}

render();

Upvotes: 4

Related Questions