Image Scaling with JavaScript

26th January 2006 | 0 Comments

I recently implemented an image scaling feature for an image archive I wrote at work. Normally, I wouldn't scale an image down in a webpage, but I wanted the user to be able to download the full size image by right-clicking. And since these images are used for graphic design, it doesn't make sense to scale them before they're placed in the archive.

The first thing I needed to do was create a container for my image.  Both the container and the image inside of it need an id.

<div id="container">
<img id="picture" src="some.jpg">
</div>

With the ids I can grab both the container's and the image's height and width. The container's dimensions are usually set in the CSS.

var box = document.getElementById("container");
var img = document.getElementById("picture");

// Grab the image's dimensions
var imgH = img.clientHeight;
var imgW = img.clientWidth;

// Find which dimension is scaled the most
var scaleH = box.clientHeight / img.clientHeight;
var scaleW = box.clientWidth / img.clientWidth;

// Scale the image
if (scaleH < scaleW) {
img.style.height = box.clientHeight + "px";
img.style.width = Math.round(imgW * scaleH) + "px";
} else {
img.style.width = box.clientWidth + "px";
img.style.height = Math.round(imgH * scaleW) + "px";
}

You now have an image scaled proportionally at run-time. There is actually a lot more to the feature I implemented at work, but this will hopefully get you started. For example a more robust version would check to see if the image needs to be scaled at all, allow the user to select zoom levels, and load the image in dynamically. If you load the image in that way you need to attach an onload event to the image to make sure its loaded before it's scaled. Enjoy!

Leave a Comment