0

I drew a video HTML5 with mp4 file source, To improve css styling and everything, I redraw the frame image of the video onto canvas in 20ms interval just like many Javascript developer does,

Example on w3schools: The Last Drawing Example

If you display it on IE10 or firefox it will display everything fine, But when I display it on Chrome (mine is the latest version 31), after some times it will crash (aw snap!)

Any idea why or is there any solution to this?

Eldon Lesley
  • 915
  • 6
  • 19
  • 38

1 Answers1

1

Use requestAnimationFrame (rAF) instead. The 20ms makes no sense. Most video runs at 30 FPS in the US (NTSC system) and at 25 FPS in Europe (PAL system). That would be 33.3ms and 40ms respectively.

That being said, rAF will attemp to run at 60 FPS (or the monitor refresh rate up to 60 Hz) so we can reduce the frame rate here by using a toggle switch.

In any case rAF will enable the drawing to be synced to the monitor so in any case it will be a better choice than setInterval/setTimeout in cases such as these.

The reason you get a crash is probably due to stacking taking place (but it could also be system related).

DEMO

var toggle = true;

function loop() {

    toggle = !toggle;
    if (toggle) {
        if (!v.paused) requestAnimationFrame(loop);
        return;
    }

    /// draw video frame every 1/30 frame
    ctx.drawImage(v, 0, 0);

    /// loop if video is playing
    if (!v.paused) requestAnimationFrame(loop);
}

Then use this simplified version of that example:

var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
var ctx = c.getContext('2d');

v.addEventListener('play', loop ,false);
Community
  • 1
  • 1