我是新手使用画布,我创建了一个简单的脚本,在画布中绘制不规则多边形,知道coord。现在我需要检测用户是否点击其中一个形状并且其中一个(每个对象都有一个ID)。您可以看到我的脚本正常运行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();
}
注意:悬停时的光标指针将不胜感激。 =)
编辑: 注意我使用的是不规则的形状,没有预定义的点数。使用圆形或正多边形的某些脚本(如链接为"可能重复和#34;的页面上的那些脚本)(具有相同长度的特定边数不能解决我的问题)。