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

How to set id for drawn canvas shape?

我看到 问题,但我不知道如何为每个圈子设置 ID 并通过 javascript 代码和 css 代码访问它们? (例如点击)

您不能为已绘制到 canvas 的内容设置 ID。

The element on its own is just a bitmap and does not provide information about any drawn objects.

如果您需要与 canvas 中的项目进行交互,您需要手动保留对所有内容绘制位置的引用,或者使用 "object picking" 之类的系统或使用内置的 hit regions.

可以通过在画圆的时候定义点击对象来解决这个问题。在绘制圆圈的循环中(参考 制作的 fiddle):

...

// push circle info as objects:
circles.push({
    id: i + "," + j,    // some ID
    x: x,
    y: y,
    radius: radius
});

...

然后:

  • 将点击处理程序添加到 canvas
  • 正确的鼠标位置
  • 循环遍历对象以确定 (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(),但后者更简单,速度也足够快。

Modified version of the same fiddle