如何设置id为画布形状drawed? [英] How to set id for canvas shape drawed?

查看:343
本文介绍了如何设置id为画布形状drawed?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个问题,我不知道我可以如何为每个圈子设置ID,并从JavaScript代码和CSS代码访问它们? (例如点击)

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)

推荐答案

您可以通过在绘制圆形时定义点击对象来解决此问题。在绘制圆圈的循环内(参考 @MonicaOlejniczak 创建的小提琴):

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

...

然后:


  • 在画布上添加点击处理程序

  • 更正鼠标位置

  • if(x,y)在圆圈内:

功能示例:
$ b

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

您可以选择使用math代替 isPointInPath(),但后者更简单,并且速度足够快。

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

这篇关于如何设置id为画布形状drawed?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆