We’re continuing a series of “How-to’s” for JavaScript beginners. In this tutorial we will explain how to proportionally resize images. Most tutorials that we have written utilize JavaScript platforms other than MooTools, so we decided to create this one using Mootools, however the function which will resize image’s size can be used with any framework (i.e. jQuery, ExtJS, script.aculo.us or just plain JavaScript.)
We will just use an <img /> tag to resize the images. The actual task of resizing an image proportionally is quite simple, but the most important thing is to calculate the size properly. At first, you should define the size of the bounding box (the maximum size of your image). Let’s say it will be 200×200 pixels:
And we have a photo with a size larger than the bounding box (size 500×313 pixels):
After the image resize we should get something like this:
So that the width of the image will be 200 pixels and height will proportionally scale and become 125 pixels. The image will look smaller, but it keeps its proportions and will still look good.
Now let’s discuss how we will be implementing this in the code. Since we may want to reuse the code at some point in the future, it is best to create a function. First, it is smart to think of all the ways it could be used, how it will work, how you will call the function and also to determine input and output values. A little thought at this time will make the coding task simpler and ensure a more flexible product.
Input parameters of the function will be: maxW, maxH (these parameters will set the size of the bounding box) and currW, currH (these parameters will contain current or original size of the image. In our sample it’s 500×313 pixels). The function will calculate size and return an array containing two values. Usage of the function will be:
{code type=php}
var newSize = scaleSize(200, 200, 500, 313);
alert(’New Width: ‘ + newSize[0] + ‘, New Height: ‘ + newSize[1]);
{/code}
Now let’s implement the algorithm of the scaleSize function. The logic is simple. You just determine the widest side (for landscape photos it will be width and for portrait photos it will be height), then set the size of bounding box to it and calculate the size of the opposite side using the following formula:
For width: currH / currH / currW;
For height: currW * currH / currW;
You will notice that currH / currW expression repeats in both calculations. This is a ratio of height to width. So, here is the actual implementation of the function:
{code type=php}
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1){
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
{/code}
That’s it ;) Click the Demo button to view the code in action.