Responsive Mapping on Image

Published On: 12 February 2014.By .
  • Digital Engineering

If an image’s width is given in % and we change the tab or window’s size it goes compressed or expanded accordingly because of the percentage width. But what about mapping on that image. It can not be given in %. Because its basically a collection of coordinates.

javascript tutorials

javascript tutorials

I will take an example of a poly area on an image.

<img src=”xx.png” style=”width:100%;” border=”0″ usemap=”#Map” id=”img” />
<map name=”Map”>
<area shape=”poly” id=”ar1″ coords=”107,64,170,65,192,87,

196,124,177,147,150,149,147,168,109,168,106,65″ href=”xyz.html”>
</map>

Basically there is an image with id “img” and on which a poly area is set as a link “xyz.html”.

the coords in the poly area is 107,64,170,65,192,87,196,124,

177,147,150,149,147,168,109,168,106,65

it is a collection of coordinates as x1,y1, x2,y2, x3,y3 ….., x9,y9
So there are 9 points or edges of that poly area on image which works as a link.

If image’s original width is 1000px and height is 600px and this poly area coordinates are calculated on that size. But as we have not set it in the image’s style attribute and set as 100% width so we will take two javascript variables baseWidth,baseHeight and set values 1000,600 to them. And write the code like below –

<script>

var baseWidth = 1000;
var baseHeight = 600;
var basepolycoords = document.getElementById(‘ar1’).coords;window.onresize = resizefunc;
function resizefunc()
{
var h = document.getElementById(‘mainMap’).offsetHeight;
var w = document.getElementById(‘mainMap’).offsetWidth;
var coords = changecoords(basepolycoords,w,h,baseWidth,baseHeight);
document.getElementById(‘ar1’).coords = coords;
}
function changecoords(coords,newx,newy,oldx,oldy)
{
var arr = new Array();
arr = coords.split(“,”);
var i=0;
for(i=0;i<arr.length;i++)
{
if(i%2==0)
{
arr[i] = parseInt((newx/oldx)*arr[i]);
}
else
{
arr[i] = parseInt((newy/oldy)*arr[i]);
}
}var str = arr.join();
                return str;
            }
resizefunc();//called to adjust coords according to its initial window size.

</script>

Related content

That’s all for this blog

Go to Top