canvas抠取视频绿幕

发布时间 2023-10-27 17:47:07作者: 菜鸟成长日记lx
最近在vue项目中遇到了一个需求就是要展示类似AI 播报的效果,用到了canvas 抠取绿幕视频,不说直接上代码
html代码
    <!-- 模拟ai播报 -->
    <video v-if='videoShow' class="noshow" ref="video" id="video" width='383' height='383' controls :src='v_url' webkit-playsinline="true" playsinline="true" x-webkit-airplay="allow" x5-video-player-type="h5" x5-video-player-fullscreen="true" x5-video-orientation="portraint" style="object-fit:fill"></video>
    <div v-draggable v-if="isShowBobao" class="bobao">
      <div class="bobao_content" :class="{'no_bg':!first_show}" style="height: 383px;width: 383px;">
        <span @click="closeAiVideo" class="close" style="right: 95px;top: 155px;"></span>
        <div v-show="true" class="top_person" style="height: 383px;width: 383px;">
          <canvas id="canvas" ref="canvas" width="383" height="383"></canvas>
        </div>
        <!-- <div v-show="false" class="overLay_person">
          <img v-show="first_show" src="../assets/image/home/ai_person.png" alt="">
        </div> -->
        <div class="bottom_btn" style="width: 383px;height: 33px;line-height: 33px;position: absolute;bottom: -40px;right: -0;">
          <div class="anniu" style="width: 140px;">
            <span @click="preVideo()"></span>
            <span :class="{'bo':isZanting,'zan':!isZanting}" @click="zanting()"></span>
            <span @click="nextVideo()"></span>
          </div>
        </div>

      </div>
    </div>

js中的代码:

 doLoad() {
      this.video = document.getElementById("video");
      this.c3 = document.getElementById("canvas");
      this.ctx3 = this.c3.getContext("2d");
      let self = this;
      this.video.addEventListener(
        "play",
        function () {
          self.width = self.video.width;
          self.height = self.video.height;
          self.timerCallback();
        },
        false
      );
    },
    timerCallback() {
      if (this.video.paused || this.video.ended) {
        return;
      }

      let self = this;
      setTimeout(function () {
        self.timerCallback();
      }, 0);
      this.computeFrame();
    },
    computeFrame() {
      this.ctx3.drawImage(this.video, 0, 0, this.width, this.height);
      var frame = this.ctx3.getImageData(0, 0, this.width, this.height);
      var data = frame.data;
      let l = frame.data.length / 4;
      // var _colors = [66, 255, 36],
      var _colors = [66, 230, 36],
        _range = 170;

      while (l--) {
        var r = data[l * 4];
        var g = data[l * 4 + 1];
        var b = data[l * 4 + 2];

        if (
          Math.abs(r - _colors[0]) < 250 - _range &&
          Math.abs(g - _colors[1]) < 250 - _range &&
          Math.abs(b - _colors[2]) < 250 - _range
        ) {
          frame.data[l * 4 + 3] = 0;
        }
      }
      this.ctx3.putImageData(frame, 0, 0);
      return;
    },

原本视频播放的效果:

 经过canvas 抠取绿幕处理成想要的样式,