Crosshair
Full-area crosshair lines that follow the pointer with eased lag and a noise distortion on link hover, with a resting position before first move.
pnpm dlx shadcn@latest add @leo/crosshairProps
| Name | Type | Default | Description |
|---|---|---|---|
| className | string | undefined | - | |
| color | string | undefined | white | |
| containerRef | RefObject<HTMLElement | null> | null | undefined | - | |
| initialPosition | { x: number; y: number; } | undefined | - | Where the lines rest before the pointer first moves, as fractions (0-1) of the container (or the window). Omitted: lines stay hidden until the first pointer move. |
Dependencies
- gsap@^3.13.0
Source
"use client";
import { gsap } from "gsap";
import React, { type RefObject, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
const lerp = (a: number, b: number, n: number): number => (1 - n) * a + n * b;
const getMousePos = (e: Event, container?: HTMLElement | null): { x: number; y: number } => {
const mouseEvent = e as MouseEvent;
if (container) {
const bounds = container.getBoundingClientRect();
return {
x: mouseEvent.clientX - bounds.left,
y: mouseEvent.clientY - bounds.top,
};
}
return { x: mouseEvent.clientX, y: mouseEvent.clientY };
};
export interface CrosshairProps {
color?: string;
containerRef?: RefObject<HTMLElement | null> | null;
/**
* Where the lines rest before the pointer first moves, as fractions (0-1) of the
* container (or the window). Omitted: lines stay hidden until the first pointer move.
*/
initialPosition?: { x: number; y: number };
className?: string;
}
const Crosshair: React.FC<CrosshairProps> = ({
color = "white",
containerRef = null,
initialPosition,
className,
}) => {
const cursorRef = useRef<HTMLDivElement>(null);
const lineHorizontalRef = useRef<HTMLDivElement>(null);
const lineVerticalRef = useRef<HTMLDivElement>(null);
const filterXRef = useRef<SVGFETurbulenceElement>(null);
const filterYRef = useRef<SVGFETurbulenceElement>(null);
let mouse = { x: 0, y: 0 };
// biome-ignore lint/correctness/useExhaustiveDependencies: the effect wires listeners once; later prop changes are not applied, as upstream
useEffect(() => {
const handleMouseMove = (ev: Event) => {
const mouseEvent = ev as MouseEvent;
mouse = getMousePos(mouseEvent, containerRef?.current);
if (containerRef?.current) {
const bounds = containerRef.current.getBoundingClientRect();
if (
mouseEvent.clientX < bounds.left ||
mouseEvent.clientX > bounds.right ||
mouseEvent.clientY < bounds.top ||
mouseEvent.clientY > bounds.bottom
) {
gsap.to([lineHorizontalRef.current, lineVerticalRef.current].filter(Boolean), {
opacity: 0,
});
} else {
gsap.to([lineHorizontalRef.current, lineVerticalRef.current].filter(Boolean), {
opacity: 1,
});
}
}
};
const target: HTMLElement | Window = containerRef?.current || window;
target.addEventListener("mousemove", handleMouseMove);
const renderedStyles: {
[key: string]: { previous: number; current: number; amt: number };
} = {
tx: { previous: 0, current: 0, amt: 0.15 },
ty: { previous: 0, current: 0, amt: 0.15 },
};
gsap.set([lineHorizontalRef.current, lineVerticalRef.current].filter(Boolean), { opacity: 0 });
let hasRestingPosition = false;
if (initialPosition) {
hasRestingPosition = true;
const bounds = containerRef?.current?.getBoundingClientRect();
const width = bounds ? bounds.width : window.innerWidth;
const height = bounds ? bounds.height : window.innerHeight;
mouse = { x: initialPosition.x * width, y: initialPosition.y * height };
gsap.set(lineVerticalRef.current, { x: mouse.x, opacity: 1 });
gsap.set(lineHorizontalRef.current, { y: mouse.y, opacity: 1 });
renderedStyles.tx.previous = mouse.x;
renderedStyles.ty.previous = mouse.y;
}
const onMouseMove = (_ev: Event) => {
// With a resting position, `previous` already holds it so the lines ease to the cursor instead of jumping.
if (!hasRestingPosition) {
renderedStyles.tx.previous = mouse.x;
renderedStyles.ty.previous = mouse.y;
}
renderedStyles.tx.current = mouse.x;
renderedStyles.ty.current = mouse.y;
gsap.to([lineHorizontalRef.current, lineVerticalRef.current].filter(Boolean), {
duration: 0.9,
ease: "Power3.easeOut",
opacity: 1,
});
rafId = requestAnimationFrame(render);
target.removeEventListener("mousemove", onMouseMove);
};
target.addEventListener("mousemove", onMouseMove);
const primitiveValues = { turbulence: 0 };
const tl = gsap
.timeline({
paused: true,
onStart: () => {
if (lineHorizontalRef.current) {
lineHorizontalRef.current.style.filter = "url(#filter-noise-x)";
}
if (lineVerticalRef.current) {
lineVerticalRef.current.style.filter = "url(#filter-noise-y)";
}
},
onUpdate: () => {
if (filterXRef.current && filterYRef.current) {
filterXRef.current.setAttribute("baseFrequency", primitiveValues.turbulence.toString());
filterYRef.current.setAttribute("baseFrequency", primitiveValues.turbulence.toString());
}
},
onComplete: () => {
if (lineHorizontalRef.current && lineVerticalRef.current) {
lineHorizontalRef.current.style.filter = "none";
lineVerticalRef.current.style.filter = "none";
}
},
})
.to(primitiveValues, {
duration: 0.5,
ease: "power1",
startAt: { turbulence: 1 },
turbulence: 0,
});
const enter = () => tl.restart();
const leave = () => {
tl.progress(1).kill();
};
let rafId = 0;
const render = () => {
renderedStyles.tx.current = mouse.x;
renderedStyles.ty.current = mouse.y;
for (const key in renderedStyles) {
const style = renderedStyles[key];
style.previous = lerp(style.previous, style.current, style.amt);
}
if (lineHorizontalRef.current && lineVerticalRef.current) {
gsap.set(lineVerticalRef.current, { x: renderedStyles.tx.previous });
gsap.set(lineHorizontalRef.current, { y: renderedStyles.ty.previous });
}
rafId = requestAnimationFrame(render);
};
const links: NodeListOf<HTMLAnchorElement> = containerRef?.current
? containerRef.current.querySelectorAll("a")
: document.querySelectorAll("a");
links.forEach((link) => {
link.addEventListener("mouseenter", enter);
link.addEventListener("mouseleave", leave);
});
return () => {
cancelAnimationFrame(rafId);
target.removeEventListener("mousemove", handleMouseMove);
target.removeEventListener("mousemove", onMouseMove);
links.forEach((link) => {
link.removeEventListener("mouseenter", enter);
link.removeEventListener("mouseleave", leave);
});
};
}, [containerRef]);
return (
<div
ref={cursorRef}
className={cn(
containerRef ? "absolute" : "fixed",
"top-0 left-0 w-full h-full pointer-events-none z-[10000]",
className,
)}
>
<svg aria-hidden="true" className="absolute top-0 left-0 w-full h-full">
<defs>
<filter id="filter-noise-x">
<feTurbulence
type="fractalNoise"
baseFrequency="0.000001"
numOctaves="1"
ref={filterXRef}
/>
<feDisplacementMap in="SourceGraphic" scale="40" />
</filter>
<filter id="filter-noise-y">
<feTurbulence
type="fractalNoise"
baseFrequency="0.000001"
numOctaves="1"
ref={filterYRef}
/>
<feDisplacementMap in="SourceGraphic" scale="40" />
</filter>
</defs>
</svg>
<div
ref={lineHorizontalRef}
className={`absolute w-full h-px pointer-events-none opacity-0 transform translate-y-1/2`}
style={{ background: color }}
></div>
<div
ref={lineVerticalRef}
className={`absolute h-full w-px pointer-events-none opacity-0 transform translate-x-1/2`}
style={{ background: color }}
></div>
</div>
);
};
export { Crosshair };
export default Crosshair;