I am new using canvas and I created a simple script to draw irregular polygons in a canvas knowing the coord. Now I need to detect if an user clicks on one of those shapes and wich one (each object has an ID). You can see my script working here.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var objetos = [];
// First Shape
objetos.push( {
id:'First',
coordinates: {
p1: {
x: 30,
y: 10
},
p2: {
x: 50,
y: 50
},
p3: {
x: 90,
y: 90
},
p4: {
x: 50,
y: 90
},
}
});
// Second Shape
objetos.push( {
id:'Two',
coordinates: {
p1: {
x: 150,
y: 20
},
p2: {
x: 90,
y: 50
},
p3: {
x: 90,
y: 30
},
}
});
// 3th Shape
objetos.push( {
id:'Shape',
coordinates: {
p1: {
x: 150,
y: 120
},
p2: {
x: 160,
y: 120
},
p3: {
x: 160,
y: 50
},
p4: {
x: 150,
y: 50
},
}
});
// Read each object
for (var i in objetos){
// Draw rhe shapes
ctx.beginPath();
var num = 0;
for (var j in objetos[i].coordinates){
if(num==0){
ctx.moveTo(objetos[i].coordinates[j]['x'], objetos[i].coordinates[j]['y']);
}else{
ctx.lineTo(objetos[i].coordinates[j]['x'], objetos[i].coordinates[j]['y']);
}
num++;
}
ctx.closePath();
ctx.lineWidth = 2;
ctx.fillStyle = '#8ED6FF';
ctx.fill();
ctx.strokeStyle = 'blue';
ctx.stroke();
}
NOTE: A cursor pointer on hover would be appreciated. =)
EDIT: Note I am using irregular shapes with no predefined number of points. Some scripts (like those on pages linked as "Possible duplication") using circles or regular polygons (certain number of sides with the same lengh do not solve my issue).