html – jQuery canvas on video background color with black color in video object-ThrowExceptions

Exception or error:

I’m working on video with background colour = black and want to show it on <canvas></canvas> with background transparent

What I already done.

  1. DrawImage from <video> to <canvas id="canvas1">
  2. I’ve draw image from <canvas id="canvas1"> to <canvas id="canvas2"> to remove a black background

The problem

  1. Black background become a transparent like I want but if in the video contain black object then, it’s gone too.

Question

  1. How to keep original color on black object inside video but make transparent for black background color

for example:

enter image description here

this is my code

HTML

<div>
   <video id="x-video" playsinline="playsinline" muted="muted" crossorigin="anonymous">
      <source type="video/mp4" src="http://techslides.com/demos/sample-videos/small.mp4">
   </video>
   <canvas id="x-canvas-1"></canvas>
   <canvas id="x-canvas-2"></canvas>
</div>

JS

let processor = {
   timerCallback: function() {
      if (this.video.paused || this.video.ended) {
          return;
      }
      this.computeFrame();
      let self = this;
      setTimeout(function () {
          self.timerCallback();
      }, 0);
   },

   doLoad: function() {
      this.video = document.getElementById("x-video");
      this.c1 = document.getElementById("x-canvas-1");
      this.ctx1 = this.c1.getContext("2d");
      this.c2 = document.getElementById("x-canvas-2");
      this.ctx2 = this.c2.getContext("2d");
      let self = this;
      this.video.addEventListener("play", function() {
         self.width = self.video.videoWidth;
         self.height = self.video.videoHeight;
         self.timerCallback();
      }, false);

      this.video.width = self.video.videoWidth;
      this.video.height = self.video.videoHeight / 4;

      this.c1.width = this.video.width;
      this.c1.height = self.video.videoHeight;

      this.c2.width = this.video.width;
      this.c2.height = self.video.videoHeight;
   },

   computeFrame: function() {
      this.ctx1.drawImage(this.video, 0, 0, this.video.videoWidth, this.video.videoHeight);
      let frame = this.ctx1.getImageData(0, 0, this.video.videoWidth, this.video.videoHeight);
      let l = frame.data.length / 4;

      for (let i = 0; i < l; i++) {
           let r = frame.data[i * 4];
           let g = frame.data[i * 4 + 1];
           let b = frame.data[i * 4 + 2];
           if (r < 20 && g < 20 && b < 20)
               frame.data[i * 4 + 3] = 0;
           }

           this.ctx2.putImageData(frame, 0, 0);
           return;
       }
    }
};

$(document).ready(function() {
      setTimeout(function () {
         processor.doLoad();

         $video[0].play();
      }, 1500);
   });
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *