Skip to content

Instantly share code, notes, and snippets.

@Honga1
Created March 4, 2020 18:09
Show Gist options
  • Save Honga1/7e383c38058f7012105540ce55c87760 to your computer and use it in GitHub Desktop.
Save Honga1/7e383c38058f7012105540ce55c87760 to your computer and use it in GitHub Desktop.
A Typescript DOM Mouse singleton. Holds and updates mouse move / touch move pointer positions.
/**
* A singleton which holds and updates mouse move / touch move pointer positions.
* Exporting or placing this in your code exposes Mouse.
*/
export class Mouse {
private static instance = new Mouse();
private position: [number, number] = [0, 0];
private constructor() {
document.addEventListener(
"mousemove",
(event: MouseEvent) => (this.position = [event.clientX, event.clientY])
);
document.addEventListener(
"touchmove",
(event: TouchEvent) =>
(this.position = [event.touches[0].clientX, event.touches[0].clientY])
);
}
/**
* Gets [X, Y] absolute mouse/touch position.
* @static
* @returns {[number, number]} [X, Y] absolute position.
* @memberof Mouse
*/
static Position(): [number, number] {
return this.instance.position;
}
/**
* Gets [X, Y] Relative mouse/touch position. Scaled from 0 - 1.
* @static
* @returns {[number, number]} [X, Y] relative positions
* @memberof Mouse
*/
static RelativePosition(): [number, number] {
const [scaleX, scaleY] = [window.innerWidth, window.innerHeight];
return [
this.instance.position[0] / scaleX,
this.instance.position[1] / scaleY
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment