| class Mouse { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| constructor(model, view, callback) { |
| Object.assign(this, { model, view, callback }) |
| this.canvas = view.canvas |
| this.world = model.world |
| |
| |
| this.callMouseHandler = e => this.mouseHandler(e) |
| |
| this.isRunning = this.mouseDown = false |
| this.x = this.y = this.action = null |
| this.setContinuous(false) |
| } |
| setContinuous(continuous = true) { |
| this.continuous = continuous |
| return this |
| } |
| |
| |
| |
| |
| |
| start() { |
| |
| this.canvas.addEventListener('mousedown', this.callMouseHandler) |
| if (this.continuous) this.startMouse() |
| this.isRunning = true |
| return this |
| } |
| |
| |
| |
| |
| |
| stop() { |
| |
| this.canvas.removeEventListener('mousedown', this.callMouseHandler) |
| this.stopMouse() |
| this.isRunning = false |
| return this |
| } |
| startMouse() { |
| document.body.addEventListener('mouseup', this.callMouseHandler) |
| this.canvas.addEventListener('mousemove', this.callMouseHandler) |
| } |
| stopMouse() { |
| document.body.removeEventListener('mouseup', this.callMouseHandler) |
| this.canvas.removeEventListener('mousemove', this.callMouseHandler) |
| } |
| |
| mouseHandler(e) { |
| if (e.type === 'mousedown') { |
| if (!this.continuous) this.startMouse() |
| this.mouseDown = true |
| } |
| if (e.type === 'mouseup') { |
| if (!this.continuous) this.stopMouse() |
| this.mouseDown = false |
| } |
| |
| this.action = e.type |
| if (e.type === 'mousemove' && this.mouseDown) { |
| this.action = 'mousedrag' |
| } |
| |
| this.setXY(e) |
| this.callback(this) |
| } |
| |
| |
| setXY(e) { |
| const { canvas, world } = this |
| const patchSize = world.patchSize(canvas) |
| const rect = this.canvas.getBoundingClientRect() |
| const pixX = e.clientX - rect.left |
| const pixY = e.clientY - rect.top |
| |
| const [x, y] = world.pixelXYtoPatchXY(pixX, pixY, patchSize) |
| Object.assign(this, { x, y }) |
| } |
| } |
| |
| export default Mouse |