how to stop canvas resizing from resizing images

Solutions on MaxInterview for how to stop canvas resizing from resizing images by the best coders in the world

showing results for - "how to stop canvas resizing from resizing images"
Jayson
09 Nov 2020
1//You just need to calculate the image aspect ratio:
2var f = image.height / image.width;
3var newHeight = canvas.width * f;
4//And then draw using the recalculated height of image for destination:
5ctx.drawImage(image, 0, 0, image.width, image.height, // source size
6                     0, 0, canvas.width, newHeight);  // destination size
7//Canvas will do the clipping for you.
8//If you want to lets say center the destination vertical position you can do:
9var destY = (canvas.height - image.height) / 2;
10ctx.drawImage(image, 0, 0, image.width, image.height,    // source size
11                     0, destY, canvas.width, newHeight); // destination size