H5截取视频第一帧作为预览图片

H5的video标签来播放视频。请问如何自动截取视频的第一帧作为视频的预览图片?

阅读 54k
7 个回答
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>capture screen</title>
</head>
<body>
<video id="video" controls="controls">
<source src="123.MP4">
</video>
<div id="output"></div>
<script type="text/javascript">
(function(){
var video, output;
var scale = 0.8;
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();
})();
</script>
</body>
</html>

来源:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
演示https://www.youtube.com/watch?v=-ZZtYNIwYBU&feature=player_detailpage#t=194s

为什么proload="meta"依然无法显示。

同问:
如果是跨域视频文件呢?
这个怎么解决?

<video id="video" controls="controls">
    <source src="http://mt-development.oss-cn-hangzhou.aliyuncs.com/chance/feeds/video/5b72370f25998.mp4">
</video>

video 有个属性 poster

poster: A URL for an image to be shown while the video is downloading.
If this attribute isn't specified, nothing is displayed until the
first frame is available, then the first frame is shown as the poster
frame.

你只要设置

<video width="620" controls

  poster="https://upload.wikimedia.org/wikipedia/commons/e/e8/Elephants_Dream_s5_both.jpg"
  <source
    src="https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4"
    type="video/mp4">
  <source
    src="https://archive.org/download/ElephantsDream/ed_hd.ogv"
    type="video/ogg">
  <source
    src="https://archive.org/download/ElephantsDream/ed_hd.avi"
    type="video/avi">
  Your browser doesn't support HTML5 video tag.
</video>

就可以设置首屏图片了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏