1. 程式人生 > >vue 擷取視訊第一幀

vue 擷取視訊第一幀

最近自己寫專案,在專案中涉及功能點又擷取視訊幀的點;需求澄清:移動端封面展示,平臺上傳圖片(多張上傳)取第一張上傳圖片為封面圖;如上傳視訊則擷取視訊第一幀作為封面圖;

實現思路;h5  video標籤,canvas;上傳視訊成功之後把返回視訊地址放到video標籤內,通過canvas畫布擷取視訊第一幀;

元件程式碼:

<el-form-item ref="videocontentvideo" style="display:none;">
              <img :src="imgurl">
              <video width="320" height="240" controls id="upvideo">
              </video>
              <img :src="modlevidel" />
            </el-form-item>
<el-form-item class="upload-demo-content" v-show="formLabelAlign.type==2">
            <el-upload class="upload-demo" :limit="1" :on-exceed="exceedhandle" drag :file-list="filsListArray" :action="configuploadurl" :on-success="successuploadhandle" accept="video" name="fileList" :before-upload="beforeUploadVideo">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">將視訊檔案拖到此處,或
                
<em>點選上傳</em> </div> <div class="el-upload__tip" slot="tip"></div> </el-upload> </el-form-item>
successuploadhandle(response, file, fileList) {
      this.formLabelAlign.video = this.modlevidel =
        response.data.fileList[
0].url; this.filsListArray = []; this.filsListArray.push({ name: this.formLabelAlign.video, url: this.formLabelAlign.video }); this.findvideocover(); },
 exceedhandle(files, fileList) {
      this.$message.error("只能上傳一個視訊額");
    },
 beforeUploadVideo(file) {
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb"
        ].indexOf(file.type) == -1
      ) {
        this.$message.error("請上傳正確的視訊格式");
        return false;
      }
    },

主要程式碼=》擷取視訊第一幀:

   findvideocover() {
      let _this = this;
      this.$nextTick(() => {
        let video = document.getElementById("upvideo");
        let source = document.createElement("source");
        // source.src = require("../../assets/5b086751dbb7af1ea8fa8d05e66fe5c3.mp4");this.formLabelAlign.video
        source.src = this.formLabelAlign.video;
        source.type = "video/mp4";
        video.appendChild(source);
        video.addEventListener("loadeddata", function() {
          var canvas = document.createElement("canvas");
          canvas.width = "320";
          canvas.height = "320";
          canvas
            .getContext("2d")
            .drawImage(video, 0, 0, canvas.width, canvas.width);
          var img = document.createElement("img");
          let imgsrc = canvas.toDataURL("image/png");
          _this.Videoframehandle(imgsrc.split(",")[1]);
        });
      });
    },

視訊預覽:

 showvideohandle() {
      this.$alert(
        `<video width="320" height="240" controls>
                      <source src="${
                        this.filsListArray[0].url
                      }"  type="video/mp4">
                      您的瀏覽器不支援 HTML5 video 標籤。
                    </video>`,
        "視訊預覽",
        {
          dangerouslyUseHTMLString: true
        }
      );
    },

效果: