I want to add images to an HTML5 canvas in a grid pattern. The canvas is square but the images are of various sizes and aspect ratios. I want to crop all the images into squares.
I have the algorithm to place the images onto the canvas as squares but the images are stretched / squeezed.
How to crop the landscape and or portrait images into squares.
Here is the algorithm:
const ctx = canvas.getContext("2d");
for (let xCell = 0; xCell < 5; xCell++) {
for (let yCell = 0; yCell < 5; yCell++) {
const x = xCell * 200;
const y = yCell * 200;
const img = new Image();
img.onload = function() {
// how to crop into squares?
ctx.drawImage(img, x, y, 200, 200);
};
img.src = 'https://source.unsplash.com/random';
}
}