0

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!

2
  • 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. Commented Jan 16, 2021 at 22:06
  • Based on how you're using .drawImage(), the drawn width and height are canvas.width / 2 and canvas.height / 2 because that's what you told the function to size it to. Commented Jan 16, 2021 at 22:09

1 Answer 1

1

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.