38 lines
1.0 KiB
JavaScript
38 lines
1.0 KiB
JavaScript
import { ref, reactive, onMounted, onUnmounted } from "vue";
|
|
import { useEventListener } from "@vueuse/core";
|
|
|
|
export function useMouseRotation() {
|
|
const cardStyle = reactive({ transform: "" });
|
|
const cardRef = ref(null);
|
|
|
|
const updateRotation = (event) => {
|
|
const rect = cardRef.value.getBoundingClientRect();
|
|
const halfWidth = rect.width / 2;
|
|
const halfHeight = rect.height / 2;
|
|
const relX = event.clientX - (rect.left + halfWidth);
|
|
const relY = event.clientY - (rect.top + halfHeight);
|
|
|
|
const rotationY = -(relX / halfWidth);
|
|
const rotationX = relY / halfHeight;
|
|
|
|
cardStyle.transform = `rotateX(${rotationX * 5}deg) rotateY(${rotationY * 5}deg)`;
|
|
};
|
|
|
|
const startTracking = (event) => {
|
|
cardRef.value = event.currentTarget;
|
|
updateRotation(event);
|
|
useEventListener(window, "mousemove", updateRotation);
|
|
};
|
|
|
|
const stopTracking = () => {
|
|
cardStyle.transform = "";
|
|
window.removeEventListener("mousemove", updateRotation);
|
|
};
|
|
|
|
return {
|
|
cardStyle,
|
|
startTracking,
|
|
stopTracking,
|
|
};
|
|
}
|