4

I am trying to add video into Fabric.js, And i'm done with that.

But one question :

How to stop or cancel requestAnimFrame() ?

Example :

var canvas = new fabric.Canvas('c');
var videoEl = document.getElementById('video');
var video = new fabric.Image(videoEl);

canvas.add(video);
video.getElement().play();

fabric.util.requestAnimFrame(function render() {
  canvas.renderAll();
  fabric.util.requestAnimFrame(render);

  var current_time = videoEl.currentTime;
  if(current_time >= 5) {
    videoEl.pause();
    console.log(current_time);
  }

});

https://jsfiddle.net/l2aelba/kro7h6rv/

This is the video will stop after 5 secs. And I will stop/cancel requestAnimFrame

Causes high CPU load

Community
  • 1
  • 1
l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • wrap your `requestAnimFrame` call in an `if(flag)` (the one inside `render`since the first one will just push its execution to the next frame and is not really needed if you want to execute `render` right now.) – Kaiido Mar 07 '16 at 10:51

1 Answers1

5

I got it now : cancelRequestAnimFrame()

window.cancelRequestAnimFrame = (function(){
    return  window.cancelAnimationFrame ||
            window.webkitCancelRequestAnimationFrame ||
            window.mozCancelRequestAnimationFrame ||
            window.oCancelRequestAnimationFrame ||
            window.msCancelRequestAnimationFrame ||
            clearTimeout
})();

var canvas = new fabric.Canvas('c');
var videoEl = document.getElementById('video');
var video = new fabric.Image(videoEl);

canvas.add(video);
video.getElement().play();

var request;
var render = function() {
    canvas.renderAll();
    request = fabric.util.requestAnimFrame(render);
    var current_time = videoEl.currentTime;
    if(current_time >= 5) {
       videoEl.pause();
       cancelRequestAnimFrame(request); <--- This
    }
}

videoEl.play();
fabric.util.requestAnimFrame(render);

Demo : https://jsfiddle.net/l2aelba/kro7h6rv/2/

l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • I'm getting error: "Property 'cancelRequestAnimFrame' does not exist on type 'Window'" in angular 6 while adding window.cancelRequestAnimFrame function at the top of .ts file. – Umesh Patadiya Feb 01 '19 at 06:19