mouseinput.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. function MouseInput() {
  2. var mouseListener = null;
  3. var mouseCanvas = null;
  4. this.attach = function(canvas, listener) {
  5. mouseListener = listener;
  6. mouseCanvas = canvas;
  7. mouseCanvas.addEventListener('mousemove', this.handleMouseMove);
  8. mouseCanvas.addEventListener('mousedown', this.handleMouseDown);
  9. mouseCanvas.addEventListener('mouseup', this.handleMouseUp);
  10. mouseCanvas.addEventListener('contextmenu', this.handleContextMenu);
  11. mouseCanvas.addEventListener('touchstart', this.handleTouchStart);
  12. mouseCanvas.addEventListener('touchmove', this.handleTouchMove);
  13. mouseCanvas.addEventListener('touchend', this.handleTouchEnd);
  14. };
  15. this.detatch = function() {
  16. mouseCanvas.removeEventListener('mousemove', this.handleMouseMove);
  17. mouseCanvas.removeEventListener('mousedown', this.handleMouseDown);
  18. mouseCanvas.removeEventListener('mouseup', this.handleMouseUp);
  19. mouseCanvas.removeEventListener('contextmenu', this.handleContextMenu);
  20. mouseCanvas.removeEventListener('touchstart', this.handleTouchStart);
  21. mouseCanvas.removeEventListener('touchmove', this.handleTouchMove);
  22. mouseCanvas.removeEventListener('touchend', this.handleTouchEnd);
  23. };
  24. this.handleMouseMove = function(event) {
  25. if(!mouseListener.hasOwnProperty("mouseMove")) { return; }
  26. mouseListener.mouseMove(mouseCanvas, event.offsetX, event.offsetY);
  27. };
  28. this.handleMouseDown = function(event) {
  29. if(!mouseListener.hasOwnProperty("mouseDown")) { return; }
  30. mouseListener.mouseDown(mouseCanvas, event.button, event.offsetX, event.offsetY);
  31. };
  32. this.handleMouseUp = function(event) {
  33. if(!mouseListener.hasOwnProperty("mouseUp")) { return; }
  34. mouseListener.mouseUp(mouseCanvas, event.button, event.offsetX, event.offsetY);
  35. };
  36. this.handleTouchStart = function(event) {
  37. if(!mouseListener.hasOwnProperty("touchStart")) { return; }
  38. mouseListener.touchStart(mouseCanvas, event.touches[0].clientX, event.touches[0].clientY);
  39. }
  40. this.handleTouchMove = function(event) {
  41. if(!mouseListener.hasOwnProperty("touchMove")) { return; }
  42. mouseListener.touchMove(mouseCanvas, event.touches[0].clientX, event.touches[0].clientY);
  43. }
  44. this.handleTouchEnd = function(event) {
  45. if(!mouseListener.hasOwnProperty("touchEnd")) { return; }
  46. mouseListener.touchEnd(mouseCanvas, event.offsetX, event.offsetY);
  47. }
  48. this.handleContextMenu = function(event) {
  49. event.preventDefault();
  50. if(!mouseListener.hasOwnProperty("contextMenu")) { return false; }
  51. mouseListener.touchEnd(mouseCanvas, event);
  52. return false;
  53. };
  54. };