Cropping Images with JavaScript

posted in: css, html, javascript | 0

Imagine you have an image on your web page. And you want to crop an area from that image and display it with a given size. And you want to do that, without the server having to do the heavy work. Well then, read on, here’s a solution.

First, check out the example.

I’m using prototype for this – it comes with loads of nice functions that make your life much easier. The following code snippets assume that you included prototype to your page.

The markup is pretty simple, it contains an image tag with an ID and a DIV which will later on contain the cropped image, with the width and height set via CSS styles:

<p>The cropped image</p>
<div id="crop" style="width:80px; height:80px;"></div>

<p>Cropped from this one</p>
<img id="img" src="bond.jpg" />

The markup will be enriched by the following JavaScript function, which does all the cropping and resizing:

function crop(img_id, crop_id, x, y, width, height) {
  $(crop_id).update('<img id="' + crop_id + '_img" src="' +
      $(img_id).getAttribute('src') + '" style="display:none" />');

  var scale_x = $(crop_id).getWidth() / width;
  var scale_y = $(crop_id).getHeight() / height;

    position: 'relative',
    overflow: 'hidden' 

  $(crop_id + '_img').setStyle({
    position: 'absolute',
    display: 'block',
    left: (-x * scale_x) + 'px',
    top: (-y * scale_y) + 'px',
    width: ($(img_id).getWidth() * scale_x) + 'px',
    height: ($(img_id).getHeight() * scale_y) + 'px'

It takes six parameters:

  • img_id: The ID of the IMG tag that contains the original image
  • crop_id: The ID of the DIV that will contain the cropped image
  • x, y: The left, top position of the area to crop in the original image
  • width, height: The size of that area

In order to crop an area from an image, just call “crop” with your parameters of choice. In the example above I’m using body.onload to do the trick:

<body onload="crop('img', 'crop', 160, 140, 60, 60)">

That’s it…