0

I have the following map:

enter image description here

What I want to do is, that given the coordinates from a mouse click event inside a div (e.g. X=80 Y=120 coordinates from the div itself), to evaluate through an "if" and do some action, I'm using this code to get the coordinates inside the div:

var parentOffset = $(this).parent().offset(); 

var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;

So now what I want to do, is if the coordinates X and Y are inside the delimiting lines, then do some action.

Any ideas? Using rectangular shapes could be also a solution.

Many thanks !

Leo
  • 956
  • 8
  • 24

2 Answers2

1

I suppose you want to know which area is clicked.

A silly approach could be generating an image/array from your image with different colors using some fill technique. Then check the color of the pixel you clicked.

gizmore
  • 88
  • 7
  • Will give this a try, and it actually could work for what I'm trying to do, thanks. – Leo Feb 12 '16 at 14:38
0

So I ended up using another solution, I first took the mouse click inside the graph, and check for the coordenates like this:

$('#img_canvas').click(function(e){     
    var parentOffset = $(this).parent().offset(); 

    var relX = e.pageX - parentOffset.left;
    var relY = e.pageY - parentOffset.top;
    console.log('[' + relX + '],[' + relY + ']');
});

So with the above code I marked every coordenate from the image, and copy and paste the text of every coordenate from the console, so that I could insert it into an array for each area.

So I ended up with coordenates for every area mentioned in the image like this:

arrayImageArea1 = [[133,198],[124,205],[130,223],[128,242],[138,240],[134,282],[148,345],[155,350]];

arrayImageArea2 = [[155,350],[136,385],[129,400],[119,418],[115,431],[112,450],[104,456],[102,486],[418,256],[388,256],[386,310],[363,319],[361,346]];

and so on...

Then with this function which I took from this question (JS- Check if Point Inside A Polygon)

function inside(point, vs) {
    var x = point[0], y = point[1];
    var inside = false;
    for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
        var xi = vs[i][0], yi = vs[i][1];
        var xj = vs[j][0], yj = vs[j][1];
        var intersect = ((yi > y) != (yj > y))
            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
    }
    return inside;
}

I could check weither the click of the mouse was inside each area like this:

$('#canvas_juego').click(function(e){       
    var parentOffset = $(this).parent().offset(); 

   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;

   if(inside([ relX, relY ], arrayImageArea1)){
        //Do the action needed...
   }
});
Community
  • 1
  • 1
Leo
  • 956
  • 8
  • 24