如何为绘制的画布形状设置id?

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)

然后:

  • 向画布添加单击处理程序
  • 正确的鼠标位置
  • 循环查找if(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;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

您可以选择使用数学而不是数学isPointInPath(),但后者更简单,并且足够快以达到此目的.

修改版的同一小提琴