简体   繁体   中英

Take a snapshot from a data-uri video

I'm trying to get a snapshot from a video data-uri

var video = document.createElement('video');
video.src = uri;

canvas = document.createElement('canvas');
canvas.style.visibility = 'hidden';
document.body.appendChild(canvas);

var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
var snapshot = canvas.toDataURL();

But this doesn't work. Why?

Although it's a Data URI and you might expect the video to load instantly, you do need to listen for the video's canPlay event ( see MDN ).

 function onFile(ev) { var file = ev.target.files[0]; console.log(); var reader = new FileReader(); reader.addEventListener('load', function() { taksVideoSnapshot(reader.result); }, false); reader.readAsDataURL(file); } function taksVideoSnapshot(videoUri) { var video = document.createElement('video'); video.addEventListener('canplay', function() { canvas = document.createElement('canvas'); canvas.style.visibility = 'hidden'; document.body.appendChild(canvas); var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, canvas.width, canvas.height); var snapshot = canvas.toDataURL(); console.log('Snapshot', snapshot.length); showThumb(snapshot); }, false); video.src = videoUri; document.body.appendChild(video); } function showThumb(snapshot) { var thumb = document.createElement('img'); thumb.src = snapshot; document.body.appendChild(thumb); } 
 <input type="file" onchange="onFile(event)"> 

Also see on JSBin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM