Files
2026-01-28 19:33:35 +13:00

24 lines
778 B
JavaScript

/**
* Canvas utility functions
*/
/**
* Get mouse position relative to canvas, accounting for scaling
* @param {MouseEvent} e - Mouse event
* @param {HTMLCanvasElement} canvas - Canvas element
* @returns {{x: number, y: number}} Mouse position clamped to canvas bounds
*/
export function getMousePos(e, canvas) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
// Calculate position even if mouse is outside canvas bounds
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
// Clamp to canvas bounds
return {
x: Math.max(0, Math.min(canvas.width, x)),
y: Math.max(0, Math.min(canvas.height, y))
};
}