如何为绘制的画布形状设置ID? [英] How to set id for drawn canvas shape?
本文介绍了如何为绘制的画布形状设置ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了这个问题,但我不知道该怎么办为每个圈子设置ID并从JavaScript代码和CSS代码访问它们? (例如点击)
I see this question and I dont know how I can set id for each circles and access them from javascript codes and css codes? (e.g. click)
推荐答案
您可以通过在绘制圆时定义点击对象来解决此问题。在循环内部绘制圆圈(请参考 @MonicaOlejniczak 制作的小提琴):
You can solve this by defining click objects when drawing the circles. Inside the loop drawing the circles (ref. the fiddle made by @MonicaOlejniczak):
...
// push circle info as objects:
circles.push({
id: i + "," + j, // some ID
x: x,
y: y,
radius: radius
});
...
然后:
- 在画布上添加点击处理程序
- 正确的鼠标位置
- 循环查找对象如果(x,y)在圆内:
函数示例:
canvas.onclick = function(e) {
// correct mouse coordinates:
var rect = canvas.getBoundingClientRect(), // make x/y relative to canvas
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0, circle;
// check which circle:
while(circle = circles[i++]) {
context.beginPath(); // we build a path to check with, but not to draw
context.arc(circle.x, circle.y, circle.radius, 0, 2*Math.PI);
if (context.isPointInPath(x, y)) {
alert("Clicked circle: " + circle.id);
break;
}
}
};
您可以选择使用数学运算符代替 isPointInPath()
,但后者更简单并且足够快速。
You can optionally use math instead of the isPointInPath()
, but the latter is simpler and is fast enough for this purpose.
Modified version of the same fiddle
这篇关于如何为绘制的画布形状设置ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文