Problems with scaling over HTML 5 canvas

I am trying to capture a frame of an html5 video to create its thumbnail, but I see some strange results when the image is displayed on the canvas.

What I see - this is the image displayed on the canvas - this is just part of the video, slightly enlarged! As seen in the image below:

Wrong scale in canvas

And the code is also impossible simply:

$(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 tried many combinations of width / height / clipping areas, etc., but everything they managed to achieve varies depending on only the top right corner of the original video.

Edit: I will announce that the original video size is 1920 x 800, and the image is the size of both the video and the canvas. I tried them in different sizes, and all the same result

Edit2: I tried several formats / videos and OS and still have the same problem, so I don't think the problem is related to any codec problem, for example

+4
source share
1 answer

Ok, I don’t know why this has any meaning for the canvas element, but for this 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 like, and the video fill the canvas area. Complete 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"; 

});

+6
source

Source: https://habr.com/ru/post/1501092/


All Articles