This article will give you a detailed introduction to the method of obtaining the first frame of video in H5 as the cover. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
1. Import the library
The code is as follows (example):
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
2.HTML part
<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>
The display effect is as shown below. As for the style, I can write it myself. I am lazy, hahahaha
<video src="" onloadeddata='vSetImg(this)' autoplay> </video> <img src="" class="video-img" alt="">
The above part of the code is to display pictures, the effect is as follows, the pictures are displayed normally
3.JS part
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 / alt="How to get the first frame of video in H5 as cover" >")[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"; }}
The attribute autoplay on the video tag is necessary, otherwise the image may not be displayed. This is what I discovered after several experiments. I used jquery for the convenience of operating elements. Of course, you can also use native ones.
Recommended learning: html video tutorial
The above is the detailed content of How to get the first frame of video in H5 as cover. For more information, please follow other related articles on the PHP Chinese website!