利用Input 实现视频上传及获取视频第一帧-视频系列(1)

2021-04-30  本文已影响0人  逸笛

手动获取视频第一帧:

<template>
    <div>
        <video controls style="width:300px;"></video>
        <img :src="imgSrc">
        <div>
            <botton @click="cutPicture">
                截图
            </botton>
        </div>
        <canvas id="myCanvas" width="343" height="200"></canvas>
    </div>
</template>
<script>
export default {
    name:"video",
    data() {
        return {
            imgSrc:''
        };
    },
    methods: {
        //截取当前帧的图片
        cutPicture(){
            let self=this;
            var v = document.querySelector("video");
            let canvas = document.getElementById('myCanvas')
            var ctx = canvas.getContext('2d');                  
            ctx.drawImage(v, 0, 0, 343, 200);
            var oGrayImg = canvas.toDataURL('image/jpeg');
            this.imgSrc = oGrayImg
        },
    }
}
</script>

自动获取视频第一帧

<template>
    <div>
        <video controls style="width:300px;"></video>
        <img :src="imgSrc">
        <div>
            <botton @click="cutPicture">
                截图
            </botton>
        </div>
        <canvas id="myCanvas" width="343" height="200"></canvas>
    </div>
</template>
<script>
export default {
    name:"video",
    data() {
        return {
            imgSrc:''
        };
    },
    methods: {
      getVideo () {
      // 获取上传文件标签
      let filesId = document.getElementById('videoupload')
      // 获取音频标签
      let video = document.getElementById('video')
      this.fileDetail = filesId.files
      let url = this.getFileURL(filesId.files[0])
      if (url) {
        this.isShowVideo = true
        // 给video标签设置src
        video.src = url
      }
      var canvas = document.getElementById('myCanvas') // 获取 canvas 对象
      const ctx = canvas.getContext('2d') // 绘制2d
      video.crossOrigin = 'anonymous' // 解决跨域问题,也就是提示污染资源无法转换视频
      video.currentTime = 1 // 第一帧
      video.oncanplay = () => {
        canvas.width = video.clientWidth // 获取视频宽度
        canvas.height = video.clientHeight // 获取视频高度
        // 利用canvas对象方法绘图
        ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight)
        // 转换成base64形式
        var oGrayImg = canvas.toDataURL('image/png') // 截取后的视频封面
        this.videoImg = [oGrayImg]
      }
    },

    getFileURL (file) {
      let getUrl = null
      if (window.createObjectURL !== undefined) {
        getUrl = window.createObjectURL(file)
      } else if (window.URL !== undefined) {
        // window.URL 标准定义
        // mozilla(firefox)
        // 获取一个http格式的url路径,这个时候就可以设置<img>中的显示
        getUrl = window.URL.createObjectURL(file)
      } else if (window.webkitURL !== undefined) {
        getUrl = window.webkitURL.createObjectURL(file)
      }
      return getUrl
    },
}
</script>
上一篇下一篇

猜你喜欢

热点阅读