温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Html5中video获取第一帧怎么作为封面

发布时间:2021-04-14 11:41:39 来源:亿速云 阅读:1191 作者:小新 栏目:web开发

这篇文章主要介绍Html5中video获取第一帧怎么作为封面,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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>

展示效果如下图,样式的话,自己写哈,我比较懒,哈哈哈哈

Html5中video获取第一帧怎么作为封面

<video src="" onloadeddata='vSetImg(this)' autoplay>
</video>
<img src="" class="video-img" alt="">

上面这部分代码是展示图片,效果如下,图片显示正常

Html5中video获取第一帧怎么作为封面

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,为了操作元素方便,当然用原生的也可以。

以上是“Html5中video获取第一帧怎么作为封面”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI