Reputation: 3885
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
Upvotes: 5
Views: 4954
Reputation: 3885
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";
});
Upvotes: 11