播放视频,canvas截图,base64转文件
播放视频:input file选择文件,video播放视频
<video id="videoPlayer" controls="controls" style="width:100%;max-height:400px;"></video>用户选择了本地视频文件后,设置video的src属性
var video = this.$refs.fileInput.files[0]; var url = URL.createObjectURL(video); console.log(url); document.getElementById("videoPlayer").src=url;截图:
vue的script中
creatImg:function() { const video = document.getElementById('videoPlayer'); const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const imgHeight = video.videoHeight; const imgWidth = video.videoWidth; ctx.drawImage(video, 0, 0, imgWidth*0.2, imgHeight*0.2); this.imgSrc = canvas.toDataURL('image/png'); // console.log('imgSrc ' + imgHeight + ' ' + imgWidth) // console.log(this.imgSrc); var blob = this.dataURLtoBlob(this.imgSrc, "image/png")//base64转blob,全局函数 var file = new File([blob], "video_image.png", { type: "image/png", lastModified: Date.now() })//blob转file return file },globalFunc.js中,此js再main.js中引用,不一定非得这么写,只是比较通用的函数没必要每个vue中都写一遍,由此到处
到处全局函数
exports.install = function(Vue, option){ Vue.prototype.dataURLtoBlob = function (dataURI,type) { var binary = atob(dataURI.split(',')[1]); var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type:type}); } }main.js中
import globalFunc from '@/components/globalFunc' Vue.use(globalFunc)由此,通过creatImg可以获得视频播放时的一帧,然后生成文件,此文件和input file选择的文件一样,可以通过format-data类型的post传输
缺点:video必须播放,不过设置visibility: hidden属性后用户就看不出来了