CanvasRenderingContext2D.drawImage() generating distorted image

128 Views Asked by At

I'm using the HTML camera API + canvas.getContext('2d').drawImage to generate 350px x 130px images.

The images are somewhere near what I want them to be, but always a little distorted. What am I doing incorrectly?

Here's my test data: Camera with box-shadow, below the img that should be equal to visible part of the camera

So my webcam is 640 x 480 px. It is being shown in a tag, and I put a gray overlay absolutely positioned over it to have this visual. I want to generate screenshots representing exactly the part not hidden by my overlay, always 350 px X 130 px. I'm using this syntax to draw my image:

const sx = (640 - 350) / 2
const sy = (480 - 130) / 2
context.drawImage(
                this.$refs.video,
                sx,
                sy,
                sx + 350,
                sy + 130,
                0,
                0,
                350,
                130
            )

It might not be clear in the screenshot, but all images I generate are a little distorted, showing more than the content from my "censored" camera. How can I debug/fix this?

1

There are 1 best solutions below

0
Bruno Lamps On

SourceWidth and SourceHeight, the 4th and 5th parameters, shouldn't be summed to sx and sy the way I was doing. The drawImage method already takes them as values relative to sx and sy. So I just changed to context.drawImage(this.$refs.video,sx,sy, 350, 130, 0, 0, 350, 130) and it made my day.

Thanks chatGPT (and my boss) for clearing this out. If anyone is facing this issue, also please take a look at MDN's documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage