On Chrome and Safari, I am not having problem generating a snapshot image of a video. However, I’ve been for hours trying several different things on Firefox, but the image always comes corrupted, with a “random color” each time.
Example minimal code – https://jsfiddle.net/4uy8j1bf/1/
Basically, I’m loading a video file into a <video
element, and then draw it on a <canvas>
, and from there, generate either a data
URL or blob
URL.
But, while Chrome and Safari have no problem getting the canvas image, Firefox always gives corrupt images, even if I seek / change the video time (any video).
The canvas image is drawn fine. It’s the generation of data/blob URL that doesn’t seem to work.
Do you know why? What can I do to get this working on Firefox?
—
Firefox:
Chrome:
The example code:
var _CANVAS = document.querySelector("#video-canvas");
var _CTX = _CANVAS.getContext("2d");
var _VIDEO = document.querySelector("#main-video");
$("#file").on('change', function() {
// Object Url as the video source
$("#main-video").attr('src', URL.createObjectURL($("#file")[0].files[0]));
// Load the video and show it
_VIDEO.load();
_VIDEO.currentTime = 0;
_VIDEO.play();
// Load metadata of the video to get video duration and dimensions
_VIDEO.addEventListener('loadedmetadata', function() {
// Set canvas dimensions same as video dimensions
_CANVAS.width = _VIDEO.videoWidth;
_CANVAS.height = _VIDEO.videoHeight;
});
_VIDEO.addEventListener('canplay', function() {
_CANVAS.style.display = 'inline';
_CTX.drawImage(_VIDEO, 0, 0, _VIDEO.videoWidth, _VIDEO.videoHeight);
// var dataUrl = _CANVAS.toDataURL('image/jpeg', 0.7);
// $('body').append('<img src="'+dataUrl+'" />');
_CANVAS.toBlob(blob => {
if (blob) {
const dataUrl = URL.createObjectURL(blob);
$('body').append('<img src="'+dataUrl+'" />')
} else {
console.log('Error creating blob from canvas');
}
}, 'image/png');
});
});