How can I get the first frame of a video file in javascript as an image?
It can be done with HTML 5 video and canvas tags:
HTML:
<input type="file" id="file" name="file">
<video id="main-video" controls>
<source type="video/mp4">
</video>
<canvas id="video-canvas"></canvas>
Javascript:
var _CANVAS = document.querySelector("#video-canvas");
var _CTX = _CANVAS.getContext("2d");
var _VIDEO = document.querySelector("#main-video");
document.querySelector("#file").addEventListener('change', function() {
// Object Url as the video source
document.querySelector("#main-video source").setAttribute('src', URL.createObjectURL(document.querySelector("#file").files[0]));
// Load the video and show it
_VIDEO.load();
// 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);
});
});