27 lines
754 B
TypeScript
27 lines
754 B
TypeScript
import type { Vector2Like } from "three";
|
|
|
|
export type NormalizedScreenPosition = {
|
|
position: Vector2Like,
|
|
screenSize: Vector2Like,
|
|
pixelSize: Vector2Like,
|
|
}
|
|
|
|
export function normalizeScreenPosition(pos: Vector2Like, viewport: DOMRect | HTMLElement): NormalizedScreenPosition {
|
|
let rect: DOMRect;
|
|
if (viewport instanceof DOMRect)
|
|
rect = viewport;
|
|
else
|
|
rect = viewport.getBoundingClientRect();
|
|
|
|
return {
|
|
position: {
|
|
x: ((pos.x - rect.left) / rect.width) * 2 - 1,
|
|
y: -((pos.y - rect.top) / rect.height) * 2 + 1,
|
|
},
|
|
screenSize: { x: rect.width, y: rect.height },
|
|
pixelSize: {
|
|
x: 2 / rect.width,
|
|
y: 2 / rect.height,
|
|
}
|
|
};
|
|
} |