I have an image map with multiple areas defined, all as polygons
I would like to calculate the distance from a point on the image (typically given by the user clicking on the image) to the closes point on the outer edge of a given area.
For my case one can make the assumption that none of the edges of the polygon intersect, thus making the task a bit easyer
Detecting if the point is inside, on or outside the area/polygon is also interesting, eg by having a negative distance if the point is inside the polygon, 0 if its on the edge.
But this is not that important for me, as it easy to detect this given that the point is given by the user clicking on the image.
The generic solution for this problem is given here - but i wonder if anyone already have a implementation in javascript for solving this with image maps and areas
I would like to do something like:
var distance = calculateDistancePointToArea( xCoord, yCoord, areaId );
And it would be an extra bonus if this worked for all the shapes possible for an area: rect, circle and poly
here's the function to calculate distance between two coordinates in javascript.
function(calculateDistancePointToArea(x2, y2, areaId))
{
var el1 = document.getElementById(areaId);
var off1 = getOffset(el1);
// center
var x1 = off1.left;
var y1 = off1.top;
// distance
var length = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
}
function getOffset( el ) {
var _x = 0;
var _y = 0;
var _w = el.offsetWidth|0;
var _h = el.offsetHeight|0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return {
top: _y,
left: _x,
width: _w,
height: _h
};
}
Hope it gives you an idea and helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With