JavaScript+HTML设置视频预览图

时间:2024-03-07 09:17:31

第一种:

设置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\');