Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop/cancel requestAnimFrame() in Fabric.js

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

like image 240
l2aelba Avatar asked Oct 16 '25 10:10

l2aelba


1 Answers

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/

like image 168
l2aelba Avatar answered Oct 18 '25 23:10

l2aelba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!