How to set id for drawn canvas shape?

房东的猫 提交于 2019-12-11 12:22:15

问题


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)


回答1:


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
});

...

Then:

  • add a click handler to canvas
  • correct mouse position
  • loop through the objects finding if (x,y) is inside the circle:

Function example:

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;
        }
    }
};

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




回答2:


You can't set an ID on something that has been drawn to a canvas.

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

If you need to interact with the items inside the canvas you need to manually keep a reference to where everything is drawn, or use a system like "object picking" or using the built in hit regions.



来源:https://stackoverflow.com/questions/28826523/how-to-set-id-for-drawn-canvas-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!