代码如下:粘贴到这个在线编辑器里,可以测试效果。
菜鸟教程在线编辑器
<div><div style="flex: 1;border: 1px solid #999; position:relative;color: #333;background-color:#FFF2B8;"><span style="position: absolute;top:45%;left:45%;">点此选择文件</span><input id="a5" type="file" accept="video/*" style="opacity:0.5;width: 100%;height: 200px;"></div><br><div style="width: 70px;text-align: center;">预览:</div><div id="b5" style="min-width: 300px;min-height: 300px;"></div></div><script>const a5=document.getElementById("a5");const b5=document.getElementById("b5");a5.onchange=(event)=>{if (!event) return;let fileList= event.target.files;if (fileList.length <= 0) return;let reader = new FileReader();reader.onload = function (event) {var listHtml = '<video id="video" style="display: none;" class="video" controls="controls">'+'<source src="'+event.target.result+'">'+'</video>'+'<div class="output"></div>';b5.innerHTML=listHtml;//创建画布var canvas = document.createElement('canvas')var video = document.getElementById("video");video.preload = true;video.autoplay = true;video.muted = true;video.setAttribute('crossOrigin', 'anonymous');//设置画布的宽和高,canvas.width = 800;canvas.height = 400;video.onloadeddata = (() => {canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)var dataURL = canvas.toDataURL('image/png')b5.innerHTML=`<img src="${dataURL}">`;// 删除掉不需要的video标签部分// b5.removeChild(video)})}reader.readAsDataURL(fileList[0]);}</script>