第一種:
設置video屬性poster
<video class="videoContent" controls poster="img/poster.png"> <source src="http://www.huazuo.com/video/brand.mp4" type="video/mp4"/>
</video>
第二種:
設置視頻第一幀為預覽圖
HTML代碼:(調整output的left和top,覆蓋在video上)
<div style ="position:relative">
<video id ="video" class="videoContent" controls> <source src="video/brand.mp4" type="video/mp4"/> </video>
<div id ="output" style ="position:absolute;left:0;left:0">
</div>
</div>
JavaScript代碼:
var video, output; var scale = 0.6; var initialize = function() { output = document.getElementById("output"); video = document.getElementById("video"); video.addEventListener('loadeddata',captureImage); }; var captureImage = function() { var canvas = document.createElement("canvas");
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight* scale;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var img = document.createElement("img");
img.src = canvas.toDataURL("image/png");
output.appendChild(img); }; initialize();
output將在視頻加載完成后顯示第一幀,可以在播放時將output隱藏
問題:
canvas繪制圖片,由於瀏覽器的安全考慮,如果在使用canvas繪圖的過程中,使用到了外域的圖片資源,那么在toDataURL()時會拋出安全異常:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
解決方法:
1、將視頻放在當前域下。
2、訪問的服務器允許,資源跨域使用,也就是說設置了CORS跨域配置,Access-Control-Allow-Origin。
然后在客戶端訪問圖片資源的時候添加
img.setAttribute('crossOrigin', 'anonymous');