Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I understand the question correctly, you want to detect when the mouse enters/leaves a shape on the canvas, correct?</p> <p>If so, then you can use simple geometric calculations, which are MUCH simpler and faster than looping over pixel data. Your rendering algorithm already has a list of all visible shapes, so you know the position, dimension and type of each shape.</p> <p>Assuming you have some kind of list of shapes, similar to what @Benjammmin' is describing, you can loop over the visible shapes and do point-inside-polygon checks:</p> <pre><code>// Track which shape is currently under the mouse cursor, and raise // mouse enter/leave events function trackHoverShape(mousePos) { var shape; for (var i = 0, len = visibleShapes.length; i &lt; len; i++) { shape = visibleShapes[i]; switch (shape.type ) { case 'arc': if (pointInCircle(mousePos, shape) &amp;&amp; _currentHoverShape !== shape) { raiseEvent(_currentHoverShape, 'mouseleave'); _currentHoverShape = shape; raiseEvent(_currentHoverShape, 'mouseenter'); return; } break; case 'rect': if (pointInRect(mousePos, shape) &amp;&amp; _currentHoverShape !== shape) { raiseEvent(_currentHoverShape, 'mouseleave'); _currentHoverShape = shape; raiseEvent(_currentHoverShape, 'mouseenter'); } break; } } } function raiseEvent(shape, eventName) { var handler = shape.events[eventName]; if (handler) handler(); } // Check if the distance between the point and the shape's // center is greater than the circle's radius. (Pythagorean theroem) function pointInCircle(point, shape) { var distX = Math.abs(point.x - shape.center.x), distY = Math.abs(point.y - shape.center.y), dist = Math.sqrt(distX * distX + distY * distY); return dist &lt; shape.radius; } </code></pre> <p>So, just call the <code>trackHoverShape</code> inside your canvas <code>mousemove</code> event and it will keep track of the shape currently under the mouse.</p> <p>I hope this helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload