Gho*_*ost 1 javascript css canvas shape
我看到了这个问题而且我不知道如何为每个圈子设置ID并从javascript代码和css代码访问它们?(例如点击)
小智 6
您可以通过在绘制圆时定义单击对象来解决此问题.在圈内绘制圆圈(参考@MonicaOlejniczak制作的小提琴):
...
// push circle info as objects:
circles.push({
id: i + "," + j, // some ID
x: x,
y: y,
radius: radius
});
...
Run Code Online (Sandbox Code Playgroud)
然后:
功能示例:
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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
您可以选择使用数学而不是数学isPointInPath(),但后者更简单,并且足够快以达到此目的.
| 归档时间: |
|
| 查看次数: |
4419 次 |
| 最近记录: |