溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Html5中video獲取第一幀怎么作為封面

發(fā)布時(shí)間:2021-04-14 11:41:39 來源:億速云 閱讀:1238 作者:小新 欄目:web開發(fā)

這篇文章主要介紹Html5中video獲取第一幀怎么作為封面,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

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 = "加載動(dòng)畫.gif";
     }}

其中video標(biāo)簽上的屬性autoplay是必要的,不然可能會(huì)圖片顯示不出來,這是我實(shí)驗(yàn)幾次發(fā)現(xiàn)的。我是使用了jquery,為了操作元素方便,當(dāng)然用原生的也可以。

以上是“Html5中video獲取第一幀怎么作為封面”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI