83 lines
1.8 KiB
JavaScript
83 lines
1.8 KiB
JavaScript
import { canvas, ctx } from './canvas'
|
|
|
|
export class Mouse {
|
|
constructor () {
|
|
this.bindEvents()
|
|
this.pos = {}
|
|
this.down = {}
|
|
this.downLast = {}
|
|
this.click = {}
|
|
}
|
|
|
|
handleDn (e) {
|
|
e.preventDefault()
|
|
let btn = e.button || 0
|
|
ctx.mouse.down['btn' + btn] = true
|
|
}
|
|
|
|
handleUp (e) {
|
|
e.preventDefault()
|
|
let btn = e.button || 0
|
|
ctx.mouse.down['btn' + btn] = false
|
|
}
|
|
|
|
handleMove (e) {
|
|
let x
|
|
let y
|
|
|
|
if (e.changedTouches) {
|
|
let touch = e.changedTouches[0]
|
|
if (touch) {
|
|
e.pageX = touch.pageX
|
|
e.pageY = touch.pageY
|
|
}
|
|
}
|
|
|
|
if (e.pageX || e.pageY) {
|
|
x = e.pageX
|
|
y = e.pageY
|
|
} else {
|
|
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft
|
|
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop
|
|
}
|
|
|
|
x -= canvas.offsetLeft
|
|
y -= canvas.offsetTop
|
|
|
|
if (ctx.oX && ctx.oY) {
|
|
x += ctx.oX
|
|
y += ctx.oY
|
|
}
|
|
|
|
ctx.mouse.pos.x = x
|
|
ctx.mouse.pos.y = y
|
|
}
|
|
|
|
bindEvents () {
|
|
canvas.addEventListener('mousemove', this.handleMove, false)
|
|
canvas.addEventListener('mousedown', this.handleDn, false)
|
|
canvas.addEventListener('mouseup', this.handleUp, false)
|
|
|
|
canvas.addEventListener('touchstart', this.handleDn, false)
|
|
canvas.addEventListener('touchend', this.handleUp, false)
|
|
canvas.addEventListener('touchcancel', this.handleUp, false)
|
|
canvas.addEventListener('touchmove', this.handleMove, false)
|
|
|
|
canvas.addEventListener('contextmenu', (e) => {
|
|
e.preventDefault()
|
|
}, false)
|
|
}
|
|
|
|
update () {
|
|
this.click = {}
|
|
for (let i in this.down) {
|
|
let dn = this.down[i]
|
|
if (!dn && this.downLast[i]) {
|
|
this.click[i] = true
|
|
}
|
|
|
|
this.downLast[i] = dn
|
|
}
|
|
}
|
|
}
|