class MouseInput { constructor() { this.mouseListener = {}; this.mouseCanvas = {}; this.position = {x: 0, y: 0}; this.handlers = {}; } attachHandler(eventName, handleFunction) { this.handlers[eventName] = handleFunction; this.mouseCanvas.addEventListener(eventName, handleFunction); } detachHandler(eventName) { this.mouseCanvas.removeEventListener(eventName, this.handlers[eventName]); delete this.handlers[eventName]; } attach(canvas, listener) { this.mouseListener = listener; this.mouseCanvas = canvas; this.attachHandler('mousemove', (event) => {this.handleMouseMove(event)}); this.attachHandler('mousedown', (event) => this.handleMouseDown(event)); this.attachHandler('mouseup', (event) => this.handleMouseUp(event)); this.attachHandler('contextmenu', (event) => this.handleContextMenu(event)); this.attachHandler('touchstart', (event) => this.handleTouchStart(event)); this.attachHandler('touchmove', (event) => this.handleTouchMove(event)); this.attachHandler('touchend', (event) => this.handleTouchEnd(event)); } detach() { this.detachHandler('mousemove'); this.detachHandler('mousedown'); this.detachHandler('mouseup'); this.detachHandler('contextmenu'); this.detachHandler('touchstart'); this.detachHandler('touchmove'); this.detachHandler('touchend'); }; handleMouseMove(event) { this.position.x = event.clientX; this.position.y = event.clientY; if (!this.mouseListener.mouseMove) { return; } this.mouseListener.mouseMove(this.mouseCanvas, event.offsetX, event.offsetY); } handleMouseDown(event) { this.position.x = event.clientX; this.position.y = event.clientY; if (!this.mouseListener.mouseDown) { return; } this.mouseListener.mouseDown(this.mouseCanvas, event.button, event.offsetX, event.offsetY); } handleMouseUp(event) { this.position.x = event.clientX; this.position.y = event.clientY; if (!this.mouseListener.mouseUp) { return; } this.mouseListener.mouseUp(this.mouseCanvas, event.button, event.offsetX, event.offsetY); }; handleTouchStart(event) { this.position.x = event.clientX; this.position.y = event.clientY; if (!this.mouseListener.touchStart) { return; } this.mouseListener.touchStart(this.mouseCanvas, event.touches[0].clientX, event.touches[0].clientY); } handleTouchMove(event) { this.position.x = event.clientX; this.position.y = event.clientY; if (!this.mouseListener.touchMove) { return; } this.mouseListener.touchMove(this.mouseCanvas, event.touches[0].clientX, event.touches[0].clientY); } handleTouchEnd(event) { this.position.x = event.clientX; this.position.y = event.clientY; if (!this.mouseListener.touchEnd) { return; } this.mouseListener.touchEnd(this.mouseCanvas, event.offsetX, event.offsetY); } handleContextMenu(event) { this.position.x = event.clientX; this.position.y = event.clientY; event.preventDefault(); if (!this.mouseListener.contextMenu) { return false; } this.mouseListener.touchEnd(this.mouseCanvas, event); return false; } };