2012-02-12 118 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