2012-02-12 73 views
1

我想弄清楚如何检测处理/处理js时鼠标在屏幕上的某个对象。在这种情况下,我正在画线。看起来处理不能将“监听器”附加到对象上,所以我必须通过某种坐标检测来完成此操作 - 但我还没有找到任何这方面的好例子。这是到目前为止我的代码:处理 - mouseOver对象

void draw() { 
for(int i = 0; i < commLength; i ++) { 
    ... 
    line(circ.x, circ.y, circ.x + dir.x, circ.y + dir.y); 
} 
} 

void mouseOver(){ 
//need to detect if mouse is over one of the lines. 
} 

回答

2

我这样做是为了检查是否鼠标从一开始就是有一定的距离,并线的端部内的方式:

boolean mouseIsOverLine(float x1, float y1, float x2, float y2) { 
    float d = dist(x1, y1, x2, y2); 
    float d1 = dist(x1, y1, mouseX, mouseY); 
    float d2 = dist(x2, y2, mouseX, mouseY); 

    // distance between vertices must be similar to sum of distances from each vertex to mouse 
    if (d1 + d2 < d + MOUSE_OVER_LINE_DISTANCE_THRESHOLD) { 
    return true; 
    } 

    return false; 
} 

,其中线从(x1, y1)(x2, y2)。该图大致显示了一个将返回假(红线)和一个返回true(绿线)的示例,具体取决于MOUSE_OVER_LINE_DISTANCE_THRESHOLD的值。鼠标坐标在每种情况下都处于橙色点。

enter image description here