var ratio = (width / img.width) * img.width; will leave the ratio equal to the width and donβt learn anything from img.width, since you are deleting the division by multiplying by the same value. This will ruin your height calculation, which will ruin the drawn image.
Try the following:
var ratio = ( width / img.width );
And you get the real ratio between canvas and image height. But I donβt think you want it.
What you want is to keep the aspect ratio (width / height) of your image the same and reduce its size. This is possible even if the canvas has a different aspect ratio, leaving unused space on the sides, top or bottom.
So, you really need to know what you should use to scale the image. Width or height.
If the image has a larger aspect ratio than the canvas, then scale using the width. This means that the width will be the same and set the height for any aspect ratio. This will cause the upper and / or lower spaces to be omitted.
If the image has a lower aspect ratio than the canvas, then scale using the height. Blah blah, the height is the same. The width of the scale. Blah blah blanks on the sides.
var imgRatio = img.width / img.height; var canRatio = canvas.width / canvas.height; var scaledWidth = img.width * (canvas.height / img.height); var scaledHeight = img.height * (canvas.width / img.height); if (imgRatio > canRatio) { context.drawImage( image, 0, 0, canvas.width, scaledHeight ); } else { context.drawImage( image, 0, 0, scaledWidth, canvas.height ); }
In addition, if you do not crop the image, use only scaling, then you need all these parameters.
http://www.w3schools.com/tags/canvas_drawimage.asp