0

I've managed to make a html5 video, transparent, drawn to canvas. The problem is that the drawing of the canvas from the video is with interval, which repeats the same function over and over again to keep the animation looping, and because of that the whole website is laggy. Is there a way to fix that?

var outputCanvas = document.getElementById('output'),
  output = outputCanvas.getContext('2d'),
  bufferCanvas = document.getElementById('buffer'),
  buffer = bufferCanvas.getContext('2d'),
  video = document.getElementById('video'),
  width = outputCanvas.width,
  height = outputCanvas.height,
  interval;

function processFrame() {
  buffer.drawImage(video, 0, 0);

  var image = buffer.getImageData(0, 0, width, height),
    imageData = image.data,
    alphaData = buffer.getImageData(0, height, width, height).data;

  for (var i = 3, len = imageData.length; i < len; i = i + 4) {
    imageData[i] = alphaData[i - 1];
  }

  output.putImageData(image, 0, 0, 0, 0, width, height);
}

video.addEventListener('play', function() {
  clearInterval(interval);
  interval = setInterval(processFrame, 50);
}, false);

video.addEventListener('ended', function() {
  video.play();
}, false);

video.play();
Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46
CritingZ
  • 388
  • 2
  • 16
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame – Lazar Nikolic Dec 04 '19 at 11:18
  • The website is still very very laggy, even if I use this and not repeating it with setInterval – CritingZ Dec 04 '19 at 11:26
  • I suggest then using web worker for all of your processFrame logic in order avoid lagging which is probably caused by main thread being suffocated. – Lazar Nikolic Dec 04 '19 at 11:39
  • You may be interested in this similar q/a: https://stackoverflow.com/questions/33687775/how-to-reduce-getimagedatas-memory-usage-when-using-canvas-to-edit-video/33727707#33727707 – Kaiido Dec 04 '19 at 14:24

0 Answers0