Wednesday, July 01, 2009

Resizing an image map when zooming an image

There are some cool libraries out there for zooming images in a HTML document, but none that I’ve seen handle resizing an image map attached to the image. My research may be incomplete so I might be recreating the wheel here, but this simple solution seems to fix the problem. Now I need to integrate with one of those libraries.

First up my HTML looks like this

      <map id="map" name="map">
        <area coords="15,92,568,247" alt="Blah" href="javascript:alert('hello');" />
        <area coords="18,259,546,432" alt="Blah" href="javascript:alert('hello 2');" />
      </map>
      <input type="button" value="+" onclick="javascript:ZoomIn();"/>
      <input type="button" value="-" onclick="javascript:ZoomOut();"/><br />
      <img src="Highlight cells.png" usemap="#map" id="image" />

And then there is some JavaScript to do the resizing, that looks like this

  <script type="text/javascript">
    function ZoomIn() {
      Zoom(1.1);
    }

    function ZoomOut() {
      Zoom(0.9);
    }

    function Zoom(amount) {
      // resize image
      var image = document.getElementById('image');
      image.height = image.height * amount;

      // resize image map
      var map = document.getElementById('map');
      for (var i = 0; i < map.areas.length; i++) {
        var area = map.areas[i];
        var coords = area.coords.split(',');
        for (var j = 0; j < coords.length; j++) {
          coords[j] = coords[j] * amount;
        }
        area.coords = coords[0] + ',' + coords[1] + ',' + coords[2] + ',' + coords[3];
      }
    }
  </script>

2 comments:

Anonymous said...

Amazing script. I am working on an android app where I needed to manage zoom for an imagemap on webview. This is a perfect solution I was looking for :). Thanks a ton for sharing this.

Doogal Bell said...

Thanks, there's a newer version available here for use with jQuery, although I don't know if it works on Android devices