66 lines
2.0 KiB
JavaScript
66 lines
2.0 KiB
JavaScript
|
import {
|
||
|
isInRegion,
|
||
|
getRelativeRegionCoordinates,
|
||
|
getAbsoluteRegionCoordinates
|
||
|
} from "./helpers.js";
|
||
|
|
||
|
export class EventHandler {
|
||
|
constructor(element) {
|
||
|
this.element = element;
|
||
|
|
||
|
this.listeners = [];
|
||
|
|
||
|
this.element.addEventListener('mousemove', e => {
|
||
|
const {
|
||
|
x,
|
||
|
y,
|
||
|
relX,
|
||
|
relY,
|
||
|
} = this.getCoordinates(e.clientX, e.clientY);
|
||
|
|
||
|
this.listeners.filter(l => l.event === 'hover' && isInRegion(relX, relY, l.region)).forEach(l => {
|
||
|
const coords = getAbsoluteRegionCoordinates(x, y, l.region, this.element.width, this.element.height);
|
||
|
const relCoords = getRelativeRegionCoordinates(relX, relY, l.region);
|
||
|
const event = {
|
||
|
x: coords.x,
|
||
|
y: coords.y,
|
||
|
relX: relCoords.x,
|
||
|
relY: relCoords.y,
|
||
|
event: e,
|
||
|
};
|
||
|
l.callback(event);
|
||
|
});
|
||
|
});
|
||
|
|
||
|
this.element.addEventListener('click', e => {
|
||
|
const event = {
|
||
|
x: e.clientX - this.element.offsetLeft,
|
||
|
y: e.clientY - this.element.offsetTop,
|
||
|
event: e,
|
||
|
};
|
||
|
this.listeners.filter(l => l.event === 'click').forEach(listener => listener.callback(event));
|
||
|
});
|
||
|
}
|
||
|
|
||
|
getCoordinates(x, y) {
|
||
|
return {
|
||
|
x: x - this.element.offsetLeft,
|
||
|
y: y - this.element.offsetTop,
|
||
|
relX: (x - this.element.offsetLeft) / this.element.clientWidth,
|
||
|
relY: (y - this.element.offsetTop) / this.element.clientHeight,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
on(type, callback, x = 0, y = 0, width = 1, height = 1) {
|
||
|
this.listeners.push({
|
||
|
event: type,
|
||
|
region: {
|
||
|
x,
|
||
|
y,
|
||
|
width,
|
||
|
height
|
||
|
},
|
||
|
callback: callback,
|
||
|
});
|
||
|
}
|
||
|
}
|