I\'m trying to upload images and have them fit into different sized boxes....To give you an idea of what the application does: People upload images and have them printed onto po
I would like to suggest you use the easyCanvas library to do this. The reason for this is that the built-in drawImage
method of context do not scale the image proportionally for you, and it involves a small dose of math to get it right, especially in cases where destination shape differs from original and you want it to cover the whole area.
I made a method in this library to handle situations such as these allowing you to draw the original image proportionally into any shape even if the shape doesn't correspond with the original.
See this demo for an live example.
In essence what you do is to draw your uploaded image into the canvas with this method:
ez.drawImageProp(image, x, y, width, height);
where width and height would be that of destination.
It also has offset parameters so you can move the image around within that shape where an offset of 0.5 is center, 0 is from left and 1 is from right:
ez.drawImageProp(image, x, y, width, height, offsetX, offsetY);
Assuming image is already available all you need to do is:
var ez = new easyCanvas('canvas'); /// provide ID of existing canvas
ez.drawImageProp(image, 0, 0, ez.width, ez.height);
Disclaimer: I am the author of easyCanvas. easyCanvas is open-source (GPL3.0 license).
Canvas's context.drawImage has a version which allows you to scale an image while you are drawing it to the canvas.
If you resize disproportionally (like you do in your example) some of your resized image will fall off the canvas. Then your kitty will look distorted (in your example: stretched vertically)
This sample code resizes proportionally by using only the width. This way your kitty is not stretched.
// calculate how much to scale the resulting image
var originalWidth=16;
var originalHeight=20;
var desiredWidth=20;
var scalingFactor = desiredWidth/originalWidth;
// scale the original size proportionally
var newWidth=originalWidth*scalingFactor;
var newHeight=originalHeight*scalingFactor;
// resize the canvas to fit the desired image size
// Note: canvas is a reference to your html canvas element
canvas.width=newWidth;
canvas.height=newHeight;
// Draw the image to the canvas
// This version of drawImage allows you to scale the original image
// while you are drawing it to the canvas.
context.drawImage(
originalImage,
0,0,originalWidth,originalHeight,
0,0,newWidth,newHeight);