These questions are similar but do not help: this, this, this, and this.
The goal is to draw an image onto a square canvas while preserving the original aspect ratio and centering the image if the original aspect ratio is not square.
For instance, take the attached 1262x2688 image. The code below resizes this to 100x100, but it distorts the aspect ratio.
The code should: (1) scale the image to fit the 100x100 canvas; (2) preserve the aspect ratio; and (3) center the image vertically and horizontally within the canvas.
// Create canvas element.
var canvas = $(document.createElement("canvas"));
// Get canvas context.
var context = canvas[0].getContext("2d");
// Set canvas size.
canvas[0].width = 100;
canvas[0].height = 100;
// Write image to canvas.
context.drawImage(image, 0, 0, newWidth, newHeight);
Image
Here's the code we used:
// Create canvas element.
var canvas = $(document.createElement("canvas"));
// Get canvas context.
var context = canvas[0].getContext("2d");
// Set canvas size.
canvas[0].width = canvasWidth;
canvas[0].height = canvasHeight;
// Set image size, must use image.naturalWidth and image.naturalHeight -- not image.width and image.height.
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
// Set scale to fit image to canvas,
const scale = Math.min(canvasWidth/imageWidth, canvasHeight/imageHeight);
// Set new image dimensions.
const scaledWidth = imageWidth * scale;
const scaledHeight = imageHeight * scale;
// Draw image in center of canvas.
context.drawImage(image, (canvasWidth - scaledWidth)/2, (canvasHeight - scaledHeight)/2, scaledWidth, scaledHeight);
To fit an image to a canvas while preserving the aspect use the following
const w = image.naturalWidth;
const h = image.naturalHeight;
// Get the min scale to fit the image to the canvas
const scale = Math.min(canvas.width / w, canvas.height / h);
// Set the transform to scale the image, and center to the canvas
ctx.setTransform(scale, 0, 0, scale, canvas.width / 2, canvas.height / 2);
// draw the image offset by half its width and height to center and fit
ctx.drawImage(image, -w / 2, -h / 2, w, h);
// to reset the transform
// ctx.setTransform(1,0,0,1,0,0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With