Reputation: 2825
I'm trying to draw a polygon with HTML5 over an <area>
of a <map>
. I need it to be the same as the area that's clicked (thus simulating a hover effect). The code I came up with is:
$("area").click(function () {
var $input = $(this);
var obj = $input.attr("coords");
var poly = '[' + obj + ']';
alert(poly);
var canvas = document.getElementById("myCanvas")
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(poly[0], poly[1]);
for (item = 2; item < poly.length - 1; item += 2) {
ctx.lineTo(poly[item], poly[item + 1])
}
ctx.closePath();
ctx.fill();
});
Now the problem is in this statement var poly = '['+obj+']';
as it works if I manually enter the coordinates instead of the obj
variable, but I need the [
and ]
around it for the function to work.
Upvotes: 1
Views: 1531
Reputation: 3269
The issue is that $input.attr("coords") is returning a string, say "10,10,100,100"
or similar. You're trying to make that an array but you're just getting a string like "[10,10,100,100]"
.
In order to make an array from the string you can use split(',')
, which will split the string every ',' and return an array, so you can just do:
var poly = $input.attr("coords").split(',');
Then poly will be an array like: ["10", "10", "100", "100"]
.
If you already had the image map data then you could just draw areas on the canvas and make them clickable rather than using the map, depends how many areas you have and what you want to do.
I'm assuming as well that you don't have any circles in the image map ...
Upvotes: 3