Guest User

Untitled

a guest
Aug 19th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. Three mouse detection techniques for HTML5 canvas, none adequate
  2. // Track which shape is currently under the mouse cursor, and raise
  3. // mouse enter/leave events
  4. function trackHoverShape(mousePos) {
  5. var shape;
  6. for (var i = 0, len = visibleShapes.length; i < len; i++) {
  7. shape = visibleShapes[i];
  8. switch (shape.type ) {
  9. case 'arc':
  10. if (pointInCircle(mousePos, shape) &&
  11. _currentHoverShape !== shape) {
  12. raiseEvent(_currentHoverShape, 'mouseleave');
  13. _currentHoverShape = shape;
  14. raiseEvent(_currentHoverShape, 'mouseenter');
  15. return;
  16. }
  17. break;
  18. case 'rect':
  19. if (pointInRect(mousePos, shape) &&
  20. _currentHoverShape !== shape) {
  21. raiseEvent(_currentHoverShape, 'mouseleave');
  22. _currentHoverShape = shape;
  23. raiseEvent(_currentHoverShape, 'mouseenter');
  24. }
  25. break;
  26. }
  27. }
  28. }
  29.  
  30. function raiseEvent(shape, eventName) {
  31. var handler = shape.events[eventName];
  32. if (handler)
  33. handler();
  34. }
  35.  
  36. // Check if the distance between the point and the shape's
  37. // center is greater than the circle's radius. (Pythagorean theroem)
  38. function pointInCircle(point, shape) {
  39. var distX = Math.abs(point.x - shape.center.x),
  40. distY = Math.abs(point.y - shape.center.y),
  41. dist = Math.sqrt(distX * distX + distY * distY);
  42. return dist < shape.radius;
  43. }
Add Comment
Please, Sign In to add comment