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