Cropping images with Javascript

A 1 minute read written by Terry October 26, 2011


In the past year or so, we’ve pretty much stopped creating interactive elements with Flash. Everything is now in Javascript and HTML5.

I’ve been converting old interactive pieces from Flash to Javascript and HTML5 in my spare time. Adapting to these new platforms has been an enjoyable challenge – but not one without frustration.

One of the more frustrating tasks was cropping and scaling images programmatically. How do you turn this:

Into this:

As it turns out, this is fairly easy to do in Javascript using the HTML canvas element.

1. Start by preloading the original image:

var loadTimer;
var imgObject = new Image();
imgObject.src = 'images/fozzie.jpg';
imgObject.onLoad = onImgLoaded();
function onImgLoaded() {
  if (loadTimer != null) clearTimeout(loadTimer);
  if (!imgObject.complete) {
    loadTimer = setTimeout(function() {
    }, 3);
  } else {

2. Once you have your image loaded, redraw the portion you need for your thumbnail image.

This method will be fired once the image is done preloading. This will call the method that crops the image, then put the returned 64-bit image into the HTML document:

function onPreloadComplete(){
  //call the methods that will create a 64-bit version of thumbnail here.
  var newImg = getImagePortion(imgObject, 120, 150, 150, 80, 2);

  //place image in appropriate div
  document.getElementById("images").innerHTML = "<img alt="" src=""+newImg+"" />";

3. Draw the entire image into a canvas object, then draw the thumbnail FROM the canvas object you create.

getImagePortion(imgObj, newWidth, newHeight, startX, startY, ratio){
 /* the parameters: - the image element - the new width - the new height - the x point we start taking pixels - the y point we start taking pixels - the ratio */
 //set up canvas for thumbnail
 var tnCanvas = document.createElement('canvas');
 var tnCanvasContext = canvas.getContext('2d');
 tnCanvas.width = newWidth; tnCanvas.height = newHeight;
 /* use the sourceCanvas to duplicate the entire image. This step was crucial for iOS4 and under devices. Follow the link at the end of this post to see what happens when you don’t do this */
 var bufferCanvas = document.createElement('canvas');
 var bufferContext = bufferCanvas.getContext('2d');
 bufferCanvas.width = imgObj.width;
 bufferCanvas.height = imgObj.height;
 bufferContext.drawImage(imgObj, 0, 0);
 /* now we use the drawImage method to take the pixels from our bufferCanvas and draw them into our thumbnail canvas */
 tnCanvasContext.drawImage(bufferCanvas, startX,startY,newWidth * ratio, newHeight * ratio,0,0,newWidth,newHeight);
 return tnCanvas.toDataURL();

4. That’s it!

That wasn’t so bad.