1.引入库
代码如下(示例):
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
2.HTML部分
<p class="upload-title mg-b10 title-all">上传视频(必填)</p> <p class="file-input-trigger" onclick="document.getElementById('uploadBtn').click()"> <p class="upload-icon">+</p> <p class="upload-text">上传文件</p> </p> <input type="file" class="upload-video" id="uploadBtn"> </p>
展示效果如下图,样式的话,自己写哈,我比较懒,哈哈哈哈
<video src="" onloadeddata='vSetImg(this)' autoplay> </video> <img src="" class="video-img" alt="">
上面这部分代码是展示图片,效果如下,图片显示正常
3.JS部分
let result$('#uploadBtn').on('change', function (e) { const file = e.target.files // console.log(file) let fr = new FileReader() fr.readAsDataURL(file[0]) //将文件读取为tata Url fr.onload = function (e) { result = e.target.result // 视屏上传 if (/video/g.test(file[0].type)) { $('.upload-img').show() $('.upload-img video').attr('src', result) $('.upload-file').hide() } }})function vSetImg(obj) { $(obj).removeAttr("poster"); var vimg = $("<img/>")[0]; captureImage(obj, vimg); $(obj).attr("poster", $(vimg).attr("src")); //展示获取的第一帧图片 $(".upload-img img").attr("src", $(vimg).attr("src")); $('.upload-img video').hide() $('.upload-img img').show()}function captureImage(video, output) { const scale = 0.8 try { var videocanvas = $("<canvas/>")[0]; videocanvas.width = video.videoWidth * scale; videocanvas.height = video.videoHeight * scale; videocanvas.getContext('2d').drawImage(video, 0, 0, videocanvas.width, videocanvas.height); output.src = videocanvas.toDataURL("image/png"); delete videocanvas; } catch (e) { output.src = "加载动画.gif"; }}
其中video标签上的属性autoplay是必要的,不然可能会图片显示不出来,这是我实验几次发现的。我是使用了jquery,为了操作元素方便,当然用原生的也可以。