我正在尝试将视频添加到Fabric.js中,而我已经完成了。

但是一个问题:

如何停止或取消requestAnimFrame()

范例:

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/

这是视频将在5秒钟后停止播放。我会停止/取消requestAnimFrame

导致高CPU负载

最佳答案

我现在知道了: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);


演示:https://jsfiddle.net/l2aelba/kro7h6rv/2/

关于javascript - 如何在Fabric.js中停止/取消requestAnimFrame(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35841147/

10-10 23:17