【发布时间】:2017-03-05 10:11:19
【问题描述】:
在画布上保存大型视频文件的屏幕截图时,似乎无法获取其 blob。当视频 blob 显示在容器上时,它工作正常。
这是JSFiddle without timeout(不起作用)
这是JSFiddle with timeout(有效)
$('#txtFileUpload').on('change', function() {
var countFiles = $(this)[0].files.length;
for (var ctr = 0; ctr < countFiles; ctr++) {
var reader = new FileReader();
readerOnLoad(reader, ctr, $(this)[0], this.files[0]);
}
});
var readerOnLoad = function(reader, ctr, fileInput, files) {
reader.onloadend = (function(ctr) {
return function(e, ctr) {
var videoIdClass = 'thumb-video-' + ctr;
var $video = $('<video />', {
'src': e.target.result,
'id': videoIdClass,
'class': videoIdClass,
}).appendTo($('.video-container')).wrap('<div class="thumb-container"></div>');
setVideoCapture($video);
};
})(ctr);
reader.readAsDataURL(fileInput.files[ctr]);
}
var setVideoCapture = function(videoElement) {
var $output;
var $canvas = document.createElement('canvas');
var $img = document.createElement('img');
$output = $('#output');
$video = videoElement.get(0);
$canvas.width = $video.videoWidth * 2;
$canvas.height = $video.videoHeight * 2;
$canvas.getContext('2d').drawImage($video, 0, 0, $canvas.width, $canvas.height);
$img.src = $canvas.toDataURL();
$output.prepend($img);
}
一个快速的解决方法是在 setVideoCapture 方法上设置一个超时,如下所示:
这行得通。
var setVideoCapture = function(videoElement) {
setTimeout(function() {
var $output;
var $canvas = document.createElement('canvas');
var $img = document.createElement('img');
$output = $('#output');
$video = videoElement.get(0);
$canvas.width = $video.videoWidth * 2;
$canvas.height = $video.videoHeight * 2;
$canvas.getContext('2d').drawImage($video, 0, 0, $canvas.width, $canvas.height);
$img.src = $canvas.toDataURL();
$output.prepend($img);
}, 2000, videoElement)
}
奇怪的是它必须在 setVideoCapture 方法内,而不是在像这样触发 setVideoCapture 方法时:
这不起作用。
reader.onloadend = (function(ctr) {
return function(e, ctr) {
var videoIdClass = 'thumb-video-' + ctr;
var $video = $('<video />', {
'src': e.target.result,
'id': videoIdClass,
'class': videoIdClass,
}).appendTo($('.video-container')).wrap('<div class="thumb-container"></div>');
setTimeout(setVideoCapture($video), 3000, $video);
};
})(ctr);
当然,不推荐使用setTimeout。应该是 setVideoCapture 方法应该只在 $video 元素已经被附加并显示在容器上时触发。
【问题讨论】:
标签: javascript jquery html5-canvas blob filereader