我正在制作一个脚本,它将拍摄mp4视频并创建第一帧的快照。这样做的目的是某些移动浏览器在加载时不会播放mp4。它将显示带有播放按钮的mp4。因此,创建快照将是移动设备的良好后备。
我已经有一个基本的摘录,并且70%的时间都可以正常工作。但是,当它不起作用时,我认为我在尝试从中获取快照的脚本存在问题缓存的视频,或尝试在视频完全加载之前捕获。有没有人建议如何做到这一点100%?我尝试推迟代码行,直到所有内容加载完毕,但有时却无法正常工作。...有所帮助的是添加了一个小的setTimeOut
...
( function( window, $ ) {
const document = window.document;
const ImgSnapshot = (el) => {
//setup variables
const $el = $(el);
const video = $el.find(".wave-animation__container").get(0);
$(video).ready( () => {
setTimeout(() => {
function createCanvas(){
//create a canvas obj
let canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d')
.drawImage(video, 0, 0, canvas.width, canvas.height);
//wait until we have the canvas object captured
return $.Deferred().resolve( canvas ).promise();
}
createCanvas().done( ( canvas ) => {
//create an image element to append
let img = document.createElement("img");
img.src = canvas.toDataURL();
img.classList.add('hide-for-medium', 'snapshot');
$el.append(img);
video.classList.add( 'show-for-medium' );
});
}, 150);
});
};
$(document).ready(function(){
$('.js-wave-animation').each(function(){
new ImgSnapshot(this);
});
});
} )( window, jQuery );
答案 0 :(得分:0)
对于这个问题,我有另一种方法。不用使用deferred
对象来检查是否已加载视频,如何使用media events
中的video
<video width="400" controls id="myvideo">
<source src="" type="video/mp4">
</video>
<script type="text/javascript">
var jqvideo = $("#myvideo");
var video = jqvideo[0];
video.addEventListener("loadeddata", function() {
console.log("loaded");
let canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
let img = document.createElement("img");
img.src = canvas.toDataURL();
$("body").append(img);
}, true);
jqvideo.find("source").attr("src", "yourvideourl.mp4");
</script>