Skip to content Skip to sidebar Skip to footer

How To Set Id For Drawn Canvas Shape?

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)

Solution 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

Solution 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.

Post a Comment for "How To Set Id For Drawn Canvas Shape?"