Question

I've got a container with a video element and a mask image over it, that looks like the following:

<div id="container">
    <img id="mask" src="/images/mask.png" width="1078" height="1508" />
    <video autoplay="" id="video"></video>
</div>

As you guys can see the mask image is 1078px width and 1508px height. The video element is also 1078px width, but just 807px height (it doesn't have to be longer).

The canvas element haves the same width and height. When I try taking a snapshot of the video and draw that snapshot and a copy of the mask image to the canvas both elements are stretched way outside the canvas bounding.

var context = canvas.getContext('2d');

// Draw video
context.drawImage(video, 0, 0);

// Get mask image and draw mask
maskObj.src = document.getElementById("mask").src;
context.drawImage(maskObj, 0, 0);

I know I can pass more parameters trough the drawImage() function, but I do not know what that other parameters are exactly for. This article says you can just pass width and height as a integer. But if I do the following:

context.drawImage(video, 0, 0, 1078, 807);
context.drawImage(maskObj, 0, 0, 1078, 1508);

It is still draws the elements way outside the canvas bounding. Can't really find out what I'm doing wrong so all the help is appreciated.

Example; enter image description here

Was it helpful?

Solution

The only way it should happen is if you set the size of your canvas with css. Try to change the size of your canvas with the html attributes, or maybe add this :

canvas.width  = 1078;
canvas.height = 1508;
var context = canvas.getContext('2d');

The resolution of a canvas only depends on those attributes. The css width and height just stretches it.

OTHER TIPS

all you got to do is to get the video dimensions and set your canvas width and height to those values like below:

var video = document.getElementById('video');

canvas.height = video.videoHeight;
canvas.width = video.videoWidth;

var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top