Reputation: 221
I would like to be able to drawImage on a HTML5 canvas element where the image is resized to the canvas width but does not adjust the height. Essentially I want it to crop the height to the canvas height rather than trying to scale the width AND height.
For example, if I drawImage on a canvas of 320 x 150. I would like my image to scale down to the width of 320 and show the first 150 px of the height.
Upvotes: 2
Views: 2270
Reputation:
You just need to calculate the image aspect ratio:
var f = image.height / image.width;
var newHeight = canvas.width * f;
And then draw using the recalculated height of image for destination:
ctx.drawImage(image, 0, 0, image.width, image.height, // source size
0, 0, canvas.width, newHeight); // destination size
Canvas will do the clipping for you.
If you want to lets say center the destination vertical position you can do:
var destY = (canvas.height - image.height) / 2;
ctx.drawImage(image, 0, 0, image.width, image.height, // source size
0, destY, canvas.width, newHeight); // destination size
Upvotes: 5