Files
odysseus/static/js/editor/canvas-coords.js
pewdiepie-archdaemon e5c99a5eee Odysseus v1.0
2026-05-31 23:58:26 +09:00

22 lines
722 B
JavaScript

/**
* Convert a pointer event's client coordinates into the canvas's
* internal pixel coordinates, accounting for current display scale.
*
* Handles both mouse and the first finger of a touch event.
*
* @param {MouseEvent|TouchEvent} e
* @param {HTMLCanvasElement} canvas
* @returns {{x: number, y: number}}
*/
export function canvasCoords(e, canvas) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
return {
x: (clientX - rect.left) * scaleX,
y: (clientY - rect.top) * scaleY,
};
}