js截取视频第一帧,Javascript如何从视频中提取帧?

Hello I have the following JS code that creates a video from a file input:

Your browser does not support the HTML5 canvas tag.

Choose Video

var loadSnippetThumb = function(event) {

var c = document.getElementById("prevImgCanvas");

var context = c.getContext('2d');

var url = URL.createObjectURL(event.target.files[0]);

var video = document.getElementById('video222');

video.src = url;

video.autoPlay = true;

}

This creates a video that plays on screen that the user has chosen to upload using the file input. I don't want the video to display on screen I just want to be able to pick out a random frame of the video and displays it on the canvas. How can I do this?

Thanks.

解决方案

Add a listener on seeked and loadeddata events and set currentTime in the loadeddata event in order to get the correct video.duration. The seeked event will get called and draw your video frame at this moment :

var video = document.createElement("video");

var canvas = document.getElementById("prevImgCanvas");

canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

video.addEventListener('loadeddata', function() {

reloadRandomFrame();

}, false);

video.addEventListener('seeked', function() {

var context = canvas.getContext('2d');

context.drawImage(video, 0, 0, canvas.width, canvas.height);

}, false);

var playSelectedFile = function(event) {

var file = this.files[0];

var fileURL = URL.createObjectURL(file);

video.src = fileURL;

}

var input = document.querySelector('input');

input.addEventListener('change', playSelectedFile, false);

function reloadRandomFrame() {

if (!isNaN(video.duration)) {

var rand = Math.round(Math.random() * video.duration * 1000) + 1;

video.currentTime = rand / 1000;

}

}

Your browser does not support the HTML5 canvas tag.

The same code in a JSFiddle here

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值