2019-08-20 17:59:26 +02:00
|
|
|
class MouseControls {
|
2020-03-21 17:22:28 +01:00
|
|
|
constructor(container) {
|
|
|
|
this.el = container || document.body;
|
|
|
|
// State
|
|
|
|
this.pos = { x: 0, y: 0 };
|
|
|
|
this.isDown = false;
|
|
|
|
this.pressed = false;
|
|
|
|
this.released = false;
|
|
|
|
// Handlers
|
|
|
|
document.addEventListener("mousemove", this.move.bind(this), false);
|
|
|
|
document.addEventListener("mousedown", this.down.bind(this), false);
|
|
|
|
document.addEventListener("mouseup", this.up.bind(this), false);
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
mousePosFromEvent({ clientX, clientY }) {
|
|
|
|
const { el, pos } = this;
|
|
|
|
const rect = el.getBoundingClientRect();
|
|
|
|
const xr = el.width / el.clientWidth;
|
|
|
|
const yr = el.height / el.clientHeight;
|
|
|
|
pos.x = (clientX - rect.left) * xr;
|
|
|
|
pos.y = (clientY - rect.top) * yr;
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
move(e) {
|
|
|
|
this.mousePosFromEvent(e);
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
down(e) {
|
|
|
|
this.isDown = true;
|
|
|
|
this.pressed = true;
|
|
|
|
this.mousePosFromEvent(e);
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
up() {
|
|
|
|
this.isDown = false;
|
|
|
|
this.released = true;
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
update() {
|
|
|
|
this.released = false;
|
|
|
|
this.pressed = false;
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
}
|
2020-01-17 21:11:15 +01:00
|
|
|
|
2020-02-29 13:45:56 +01:00
|
|
|
module.exports = MouseControls;
|