35 lines
1.0 KiB
JavaScript
35 lines
1.0 KiB
JavaScript
// onPointerDown
|
|
export function useDragMove({ ref, x, y, changeXFn, changeYFn }) {
|
|
return function (e) {
|
|
e.preventDefault();
|
|
const container = ref.current;
|
|
if (!container) return;
|
|
|
|
const rect = container.getBoundingClientRect();
|
|
const startX = e.clientX;
|
|
const startY = e.clientY;
|
|
const initialX = x;
|
|
const initialY = y;
|
|
|
|
const onPointerMove = (moveEvent) => {
|
|
const deltaX = ((moveEvent.clientX - startX) / rect.width) * 100;
|
|
const deltaY = ((moveEvent.clientY - startY) / rect.height) * 100;
|
|
|
|
// clamp between 0% and 100%
|
|
const newX = Math.min(100, Math.max(0, initialX + deltaX));
|
|
const newY = Math.min(100, Math.max(0, initialY + deltaY));
|
|
|
|
changeXFn(newX);
|
|
changeYFn(newY);
|
|
};
|
|
|
|
const onPointerUp = () => {
|
|
window.removeEventListener("pointermove", onPointerMove);
|
|
window.removeEventListener("pointerup", onPointerUp);
|
|
};
|
|
|
|
window.addEventListener("pointermove", onPointerMove);
|
|
window.addEventListener("pointerup", onPointerUp);
|
|
};
|
|
}
|