Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Three mouse detection techniques for HTML5 canvas, none adequate
- // 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 < len; i++) {
- shape = visibleShapes[i];
- switch (shape.type ) {
- case 'arc':
- if (pointInCircle(mousePos, shape) &&
- _currentHoverShape !== shape) {
- raiseEvent(_currentHoverShape, 'mouseleave');
- _currentHoverShape = shape;
- raiseEvent(_currentHoverShape, 'mouseenter');
- return;
- }
- break;
- case 'rect':
- if (pointInRect(mousePos, shape) &&
- _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 < shape.radius;
- }
Add Comment
Please, Sign In to add comment