To compute the target location to draw an image into a canvas such that the image is centered and not resized, you would use something like:
let x = (canvas.width - img.width) / 2;
let y = (canvas.height - img.height) / 2;
context.drawImage(img, x, y);
If you want to draw the image both resized and centered, you’d use something like:
let width = 100;
let height = 100;
let x = (canvas.width - width) / 2;
let y = (canvas.height - height) / 2;
context.drawImage(img, x, y, width, height);
See .drawImage()
.
so I have a large image that I’m drawing onto my canvas.
context.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width / 2, canvas.height / 2);
I’m trying to use the images height and width to center it within the canvas, but when I do that, it does not work because img.naturalHeight, clientHeight, and height all give me the original pictures height of more than 5000 pixels. But I instead need the height of the image after its drawn onto the canvas otherwise when I position with 5000 pixels from the left or the top it goes way out of the canvas’ viewport.
If anyone has any insight they could share I would be very grateful. Thanks guys!
Once the image is drawn into the canvas, that drawing becomes a part of the canvas, undifferentiated from anything else that had been previously drawn to the canvas.