I'm trying to capture a frame of an html5 video in order to create a thumbnail of it but I'm seeing some strange results when the image is rendered to canvas.
What I'm seeing is the image displayed in canvas is just a section of the video scaled up quite a bit! As seen in the image below:
And the code is impossibly simple as well:
$(document).ready(function(){
var $Body = $("body");
var $Video = $("<video>").appendTo($Body);
var cVideo = $Video.get(0);
cVideo.addEventListener("loadedmetadata", function(){
cVideo.addEventListener("seeked", function(){
var $Canvas = $("<canvas>").width(cVideo.videoWidth).height(cVideo.videoHeight);
$Canvas.appendTo($Body);
var cCtx = $Canvas.get(0).getContext("2d");
cCtx.drawImage(cVideo, 0, 0);
}, false);
cVideo.currentTime = 500;
}, false);
cVideo.src = "movie.mkv";
});
I have tried many combinations of widths/heights/clipping regions etc but all im able to achieve is varying version of looking at only the top right corner of the original video.
Edit: I will ad that the original video size is 1920 x 800 and in the image provided that is the size of both the video and canvas tags. I have tried them at different sizes as well and still the same result
Edit2: I have tried multiple formats/videos and OSs and still have the same problem so I don't believe the problem to be related to any codec issue for example
Supported Video Formats The Canvas media player supports H. 264 video playback.
The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.
Set the Size with CSSto set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.
Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .
Okay I don't know why this makes any difference to the canvas element but for this to work I had to set the width and height of the canvas using its width/height attributes and then I could change the size of the canvas as I please and the video would fill the area of the canvas. Full solution below:
$(document).ready(function(){
var $Body = $("body");
var $Video = $("<video>").appendTo($Body);
var cVideo = $Video.get(0);
cVideo.addEventListener("loadedmetadata", function(){
cVideo.addEventListener("seeked", function(){
var $Canvas = $("<canvas>").attr("width", cVideo.videoWidth).attr("height", cVideo.videoHeight);
$Canvas.appendTo($Body);
var cCtx = $Canvas.get(0).getContext("2d");
cCtx.drawImage(cVideo, 0, 0, cVideo.videoWidth, cVideo.videoHeight);
}, false);
cVideo.currentTime = 500;
}, false);
cVideo.src = "movie.mkv";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With