Wednesday, February 20, 2013

Dynamically Rescaling Image Maps!

This was created for a square image. For a rectangular image, you'll want to scale every other coordinate accordingly. This script dynamically rescales the image AND the image MAP (area tag). In addition, it centers the image horizontally and vertically. The image map can be easily created in GIMP (Filters -> Web -> Image Map). Then, just save your polygon coordinates into the respective a[*].coords position. If you use rects, change the shape type. If it doesn't quite line up (shifted a bit top-left), add something like 4 to all of the coordinates for that polygon. Also, note that it doesn't need jquery!


<html>
<head>
<style>

body {background-color: black; overflow:hidden; padding: 0px; margin:0px;}
map { horizontal-align: center;}
img {position: absolute;
    top: 0; bottom:0; left: 0; right:0;
    margin: auto;}

</style>
</head>
<body>

<img src="PathTo/YourImage.jpgORpngOR..." width="1000" height="1000" border="0" usemap="#map">


<map name="map">

</map>

<script type="text/javascript">

function fixMapAndScale(){

  var img = document.getElementsByTagName("img")[0];

  var width = window.innerWidth;
  var height = window.innerHeight;
  var scale;

  if ( width>height ){ scale = height; }
  else { scale=width; }

  img.height = scale;
  img.width = scale;
  
  var a = [];

//This is the StackOverflow logo as seen on http://quantumfractal.info
  a[0] = {shape:"'poly'", coords:[29,10,126,10,129,72,103,90,62,144,21,160,11,101,44,81,32,72], href:"http://YourURL.com/whatever", title:"StackOverflow"}

  
  for(i=0; i<a.length; i++){
    for(j=0; j<a[i].coords.length; j++){
      a[i].coords[j] = Math.floor(a[i].coords[j]*(scale/1000));
    } // You'd change 1000 to whatever the dimensions of your square are.
  } // Or, you'd augment this loop for rectangle...


  var str="";
  for(i=0; i<a.length; i++){
    str += "<area id='test' shape=" + a[i].shape + " coords="+ a[i].coords.join(",") + " href=" + a[i].href+" title="+ a[i].title+">";
  }

  document.getElementsByTagName("map")[0].innerHTML = str;
}
fixMapAndScale();
window.onresize=function(){fixMapAndScale();};

</script>
</body>
</html>