Skip to content

Commit

Permalink
cursor tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
dragoni7 committed Sep 22, 2024
1 parent 2235634 commit c42dc10
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/components/CustomCursor.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import cursorImage from '../../public/assets/cursor.png';
import React, { useEffect, useRef } from 'react';
import cursorImage from '/assets/cursor.png';
import React, { useEffect, useRef, useState } from 'react';

const CustomCursor: React.FC = () => {
const cursorRef = useRef<HTMLDivElement>(null);
const [visible, setVisible] = useState<boolean>(true);

useEffect(() => {
const cursor = cursorRef.current;
Expand All @@ -17,18 +18,34 @@ const CustomCursor: React.FC = () => {
document.head.appendChild(style);

const updateCursor = (e: MouseEvent) => {
if (!visible) return;
requestAnimationFrame(() => {
cursor.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
});
};

window.addEventListener('mousemove', updateCursor);
document.addEventListener('mouseleave', () => setVisible(false));
document.addEventListener('mouseenter', () => setVisible(true));

const handleVisibilityChange = () => {
if (document.hidden) {
setVisible(false);
} else {
setVisible(true);
}
};

document.addEventListener('visibilitychange', handleVisibilityChange);

return () => {
window.removeEventListener('mousemove', updateCursor);
document.removeEventListener('mouseleave', () => setVisible(false));
document.removeEventListener('mouseenter', () => setVisible(true));
document.removeEventListener('visibilitychange', handleVisibilityChange);
document.head.removeChild(style);
};
}, []);
}, [visible]);

return (
<div
Expand All @@ -38,15 +55,15 @@ const CustomCursor: React.FC = () => {
height: '32px',
position: 'fixed',
pointerEvents: 'none',
zIndex: 9999,
zIndex: 99999,
backgroundImage: `url(${cursorImage})`,
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
top: 0,
left: 0,
transform: 'translate(-50%, -50%)',
transition: 'transform 0.1s ease-out',
transition: 'transform 0.05s ease-out',
willChange: 'transform',
display: visible ? 'block' : 'none',
}}
/>
);
Expand Down

0 comments on commit c42dc10

Please sign in to comment.