【你不知道的canvas】之更換綠屏視頻背景

canvas Api 簡單介紹

ImageData對象中存儲着canvas對象真實的像素數據,它包含如下幾個只讀屬性:前端

width:圖片寬度,單位是像素
height:圖片高度,單位是像素
dataUint8ClampedArray類型的一維數組,包含着RGBA格式的整型數據,範圍在0至255之間(包括255)。git

data屬性返回一個 Uint8ClampedArray,它能夠被使用做爲查看初始像素數據。每一個像素用4個1bytes值(按照紅,綠,藍和透明值的順序; 這就是"RGBA"格式) 來表明。每一個顏色值部份用0至255來表明。每一個部份被分配到一個在數組內連續的索引,左上角像素的紅色部份在數組的索引0位置。像素從左到右被處理,而後往下,遍歷整個數組。github

簡單來講,咱們須要每隔4個爲一組來取出每一個像素點的rgbacanvas

而後咱們結合canvas用來操做視頻的特性,來進行綠幕摳圖換背景。數組

先上效果圖:ide

image.png

代碼地址gitee
預覽地址canvas-viide,gitee最近整治giteepage,先用github的了this

實現思路

視頻==>視頻截圖==>處理綠色像素爲透明==>貼圖至背景圖上方
將視頻進行截圖,再將視頻中像素爲綠色的像素塊變爲透明
再將處理好圖片放在事先準備好的背景圖上方spa

實現

1.準備視頻以及畫布

<body onload="processor.doLoad()">
    <div>
      <video id="video" src="./q.mp4" width="350" controls="true"></video>
    </div>
    <div>
      <!-- 視頻截圖 -->
      <canvas id="c1" width="260" height="190"></canvas>
      <!-- 處理綠色像素爲透明 -->
      <canvas id="c2" width="260" height="190"></canvas>
      <!-- 貼圖至背景圖上方 -->
      <canvas id="c3" width="260" height="190"></canvas>
    </div>
</body>

2.添加視頻播放監聽

doLoad: function doLoad() {
  this.video = document.getElementById("video");
  this.c1 = document.getElementById("c1");
  this.ctx1 = this.c1.getContext("2d");
  this.c2 = document.getElementById("c2");
  this.ctx2 = this.c2.getContext("2d");
  this.c3 = document.getElementById("c3");
  this.ctx3 = this.c3.getContext("2d");
  let self = this;
  this.video.addEventListener(
    "play",
    function() {
      self.width = self.video.videoWidth / 5;
      self.height = self.video.videoHeight / 3;
      self.timerCallback();
    },
    false
  );
}

3.添加計時器

視頻播放後進行調用,進行每一幀的截圖抓取code

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

4.進行視頻幀操做

將綠色背景設置爲透明,並貼圖至自定義背景圖上視頻

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

  for (let i = 0; i < l; i++) {
    let r = frame.data[i * 4 + 0];
    let g = frame.data[i * 4 + 1];
    let b = frame.data[i * 4 + 2];
    //rgb(8 204 4)
    if (r > 4 && g > 100 && b < 100) {
      frame.data[i * 4 + 3] = 0;
    }
  }
  this.ctx2.putImageData(frame, 0, 0);
  this.ctx3.putImageData(frame, 0, 0);
  return;
}

5.微調

//rgb(8 204 4)
    綠色的視頻顏色不純,不是一直都是rgb(8 204 4),因此進行了簡單的微調。。
    if (r > 4 && g > 100 && b < 100) {
      frame.data[i * 4 + 3] = 0;
    }

結尾

更多問題歡迎加入前端交流羣交流749539640
代碼地址:gitee
預覽地址:canvas-viide
綠幕視頻下載:pixabay

相關文章
相關標籤/搜索