Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(flickering-grid): fix flickering grid resize #310

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 54 additions & 42 deletions registry/components/magicui/flickering-grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ interface FlickeringGridProps {
width?: number;
height?: number;
className?: string;

maxOpacity?: number;
}

Expand All @@ -30,7 +31,9 @@ const FlickeringGrid: React.FC<FlickeringGridProps> = ({
maxOpacity = 0.3,
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [isInView, setIsInView] = useState(false);
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });

const memoizedColor = useMemo(() => {
const toRGBA = (color: string) => {
Expand All @@ -43,39 +46,30 @@ const FlickeringGrid: React.FC<FlickeringGridProps> = ({
if (!ctx) return "rgba(255, 0, 0,";
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;
const [r, g, b] = Array.from(ctx.getImageData(0, 0, 1, 1).data);
return `rgba(${r}, ${g}, ${b},`;
};
return toRGBA(color);
}, [color]);

const setupCanvas = useCallback(
(canvas: HTMLCanvasElement) => {
const canvasWidth = width || canvas.clientWidth;
const canvasHeight = height || canvas.clientHeight;
(canvas: HTMLCanvasElement, width: number, height: number) => {
const dpr = window.devicePixelRatio || 1;
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
canvas.style.width = `${canvasWidth}px`;
canvas.style.height = `${canvasHeight}px`;
const cols = Math.floor(canvasWidth / (squareSize + gridGap));
const rows = Math.floor(canvasHeight / (squareSize + gridGap));
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
const cols = Math.floor(width / (squareSize + gridGap));
const rows = Math.floor(height / (squareSize + gridGap));

const squares = new Float32Array(cols * rows);
for (let i = 0; i < squares.length; i++) {
squares[i] = Math.random() * maxOpacity;
}

return {
width: canvasWidth,
height: canvasHeight,
cols,
rows,
squares,
dpr,
};
return { cols, rows, squares, dpr };
},
[squareSize, gridGap, width, height, maxOpacity],
[squareSize, gridGap, maxOpacity],
);

const updateSquares = useCallback(
Expand Down Expand Up @@ -121,13 +115,23 @@ const FlickeringGrid: React.FC<FlickeringGridProps> = ({

useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const container = containerRef.current;
if (!canvas || !container) return;

const ctx = canvas.getContext("2d");
if (!ctx) return;

let animationFrameId: number;
let { width, height, cols, rows, squares, dpr } = setupCanvas(canvas);
let gridParams: ReturnType<typeof setupCanvas>;

const updateCanvasSize = () => {
const newWidth = width || container.clientWidth;
const newHeight = height || container.clientHeight;
setCanvasSize({ width: newWidth, height: newHeight });
gridParams = setupCanvas(canvas, newWidth, newHeight);
};

updateCanvasSize();

let lastTime = 0;
const animate = (time: number) => {
Expand All @@ -136,48 +140,56 @@ const FlickeringGrid: React.FC<FlickeringGridProps> = ({
const deltaTime = (time - lastTime) / 1000;
lastTime = time;

updateSquares(squares, deltaTime);
drawGrid(ctx, width * dpr, height * dpr, cols, rows, squares, dpr);
updateSquares(gridParams.squares, deltaTime);
drawGrid(
ctx,
canvas.width,
canvas.height,
gridParams.cols,
gridParams.rows,
gridParams.squares,
gridParams.dpr,
);
animationFrameId = requestAnimationFrame(animate);
};

const handleResize = () => {
({ width, height, cols, rows, squares, dpr } = setupCanvas(canvas));
};
const resizeObserver = new ResizeObserver(() => {
updateCanvasSize();
});

resizeObserver.observe(container);

const observer = new IntersectionObserver(
const intersectionObserver = new IntersectionObserver(
([entry]) => {
setIsInView(entry.isIntersecting);
},
{ threshold: 0 },
);

observer.observe(canvas);

window.addEventListener("resize", handleResize);
intersectionObserver.observe(canvas);

if (isInView) {
animationFrameId = requestAnimationFrame(animate);
}

return () => {
window.removeEventListener("resize", handleResize);
cancelAnimationFrame(animationFrameId);
observer.disconnect();
resizeObserver.disconnect();
intersectionObserver.disconnect();
};
}, [setupCanvas, updateSquares, drawGrid, width, height, isInView]);

return (
<canvas
ref={canvasRef}
className={`size-full pointer-events-none ${className}`}
style={{
width: width || "100%",
height: height || "100%",
}}
width={width}
height={height}
/>
<div ref={containerRef} className={`w-full h-full ${className}`}>
<canvas
ref={canvasRef}
className="pointer-events-none"
style={{
width: canvasSize.width,
height: canvasSize.height,
}}
/>
</div>
);
};

Expand Down