Naravno! Evo poboljšane verzije vašeg React komponenta za snežne pahuljice, zajedno sa detaljnim objašnjenjem promena koje sam napravio:
Poboljšani Kod
typescript
"use client";
import React, { useEffect, useRef, useState, useMemo, useCallback } from "react";
import { useTheme } from "next-themes";
interface Snowflake {
x: number;
y: number;
size: number;
speed: number;
wind: number;
opacity: number;
shape: number;
}
interface SnowProps {
maxSnowflakes?: number;
minSize?: number;
maxSize?: number;
minSpeed?: number;
maxSpeed?: number;
minWind?: number;
maxWind?: number;
minOpacity?: number;
maxOpacity?: number;
color?: string;
zIndex?: number;
showInLightMode?: boolean;
}
const Snow: React.FC<SnowProps> = ({
maxSnowflakes = 150,
minSize = 1,
maxSize = 4,
minSpeed = 0.1,
maxSpeed = 0.5,
minWind = -0.1,
maxWind = 0.1,
minOpacity = 0.3,
maxOpacity = 0.8,
color = "#ffffff",
zIndex = 9999,
showInLightMode = false,
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const { theme, systemTheme } = useTheme();
const [mounted, setMounted] = useState(false);
// Set mounted to true after component mounts to ensure it's running on the client
useEffect(() => {
setMounted(true);
}, []);
// Memoize snowflake shapes to avoid recalculating on every render
const snowflakeShapes = useMemo(() => {
const shapes: HTMLCanvasElement[] = [];
for (let i = 0; i < 5; i++) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) continue;
canvas.width = 20;
canvas.height = 20;
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.beginPath();
for (let j = 0; j < 6; j++) {
ctx.moveTo(10, 10);
ctx.lineTo(10, 0);
ctx.moveTo(10, 3);
ctx.lineTo(7, 6);
ctx.moveTo(10, 3);
ctx.lineTo(13, 6);
ctx.rotate((Math.PI * 2) / 6);
}
ctx.stroke();
shapes.push(canvas);
}
return shapes;
}, [color]);
// Function to create a new snowflake
const createSnowflake = useCallback(
(canvasWidth: number, canvasHeight: number): Snowflake => ({
x: Math.random() * canvasWidth,
y: Math.random() * canvasHeight - canvasHeight,
size: Math.random() * (maxSize - minSize) + minSize,
speed: Math.random() * (maxSpeed - minSpeed) + minSpeed,
wind: Math.random() * (maxWind - minWind) + minWind,
opacity: Math.random() * (maxOpacity - minOpacity) + minOpacity,
shape: Math.floor(Math.random() * snowflakeShapes.length),
}),
[maxSize, minSize, maxSpeed, minSpeed, maxWind, minWind, maxOpacity, minOpacity, snowflakeShapes.length]
);
useEffect(() => {
if (!mounted) return;
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
let animationFrameId: number;
const snowflakes: Snowflake[] = [];
// Function to resize the canvas to fit the window
const resizeCanvas = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
// Debounce the resize to prevent excessive recalculations
let resizeTimeout: number;
const handleResize = () => {
clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(() => {
resizeCanvas();
}, 100);
};
// Function to draw a single snowflake
const drawSnowflake = (flake: Snowflake) => {
ctx.save();
ctx.globalAlpha = flake.opacity;
ctx.drawImage(
snowflakeShapes[flake.shape],
flake.x - flake.size,
flake.y - flake.size,
flake.size * 2,
flake.size * 2
);
ctx.restore();
};
// Function to update the position of a snowflake
const updateSnowflake = (flake: Snowflake) => {
flake.y += flake.speed;
flake.x += Math.sin(flake.y * 0.01) * flake.wind;
// Reset snowflake if it moves below the canvas
if (flake.y > canvas.height) {
Object.assign(flake, createSnowflake(canvas.width, canvas.height));
flake.y = -flake.size;
}
// Wrap around the snowflake horizontally
if (flake.x > canvas.width) flake.x = 0;
if (flake.x < 0) flake.x = canvas.width;
};
// Animation loop
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Ensure we don't exceed the maximum number of snowflakes
if (snowflakes.length < maxSnowflakes) {
snowflakes.push(createSnowflake(canvas.width, canvas.height));
}
snowflakes.forEach((flake) => {
drawSnowflake(flake);
updateSnowflake(flake);
});
animationFrameId = requestAnimationFrame(animate);
};
// Start the snow animation
const startSnowAnimation = () => {
resizeCanvas();
window.addEventListener("resize", handleResize, { passive: true });
animate();
};
// Stop the snow animation
const stopSnowAnimation = () => {
cancelAnimationFrame(animationFrameId);
window.removeEventListener("resize", handleResize);
ctx.clearRect(0, 0, canvas.width, canvas.height);
};
// Determine the current theme
const currentTheme = theme === "system" ? systemTheme : theme;
// Start or stop the animation based on the theme
if (currentTheme === "dark" || (showInLightMode && currentTheme === "light")) {
startSnowAnimation();
} else {
stopSnowAnimation();
}
// Cleanup on unmount or when dependencies change
return () => {
stopSnowAnimation();
clearTimeout(resizeTimeout);
};
}, [
theme,
systemTheme,
mounted,
maxSnowflakes,
createSnowflake,
snowflakeShapes,
showInLightMode,
]);
if (!mounted) return null;
const currentTheme = theme === "system" ? systemTheme : theme;
if (currentTheme !== "dark" && !(showInLightMode && currentTheme === "light")) return null;
return (
<canvas
ref={canvasRef}
style={{
position: "fixed",
top: 0,
left: 0,
pointerEvents: "none",
zIndex,
width: "100%",
height: "100%",
}}
/>
);
};
export default React.memo(Snow);
Objašnjenje Promena i Poboljšanja
Ispravljen Sintaksni Greške:
"use client": Prvobitno ste imali dvostruke navodnike ""use client";, što je sintaksna greška. Ispravljeno je na “use client"; koristeći jedne navodnike.
Debounce za Resize Event:
Problem: Bez debounce-a, stanje plašaka bi se moglo preopteretiti pri brzim resize događajima.
Rešenje: Dodao sam debounce funkciju koja odgađa izvršavanje resizeCanvas funkcije za 100ms nakon posljednjeg resize događaja. Ovo smanjuje broj puta kada se canvas resizuje, što poboljšava performanse.
Problem: Bez useCallback, funkcija createSnowflake bi se redefinisala na svakom renderovanju, što može dovesti do nepotrebnih ponovnih kreiranja snežnih pahuljica.
Rešenje: Korišćenjem useCallback memoizujem createSnowflake funkciju kako bi se izbeglo njeno redefinisanje osim kada se relevantni zavisnosti promene.
Sa ovim poboljšanjima, vaš komponent bi trebao biti efikasniji, lakše održiv i bez potencijalnih memorijskih curenja. Debounce funkcija za resize smanjuje broj poziva funkcije resize, korišćenjem useCallback osigurava se da se funkcije ne redefinišu nepotrebno, dok ctx.save() i ctx.restore() osiguravaju da se kontekst pravilno upravlja tokom crtanja.
Ako imate dodatnih pitanja ili želite dalje optimizacije, slobodno se javite!
Resetovanje globalAlpha koristeći ctx.save() i ctx.restore():
Problem: Postavljanje ctx.globalAlpha direktno može uticati na druge crtanje operacije koje koriste isti kontekst.
Rešenje: Pre nego što se postavi globalAlpha, koristim ctx.save(), a zatim ctx.restore() nakon crtanja kako bih osigurao da promene ne utiču na ostatak konteksta.
Problem: Originalni kod dodavao je nove pahuljke dokle god je broj manji od maxSnowflakes, ali bez ograničavanja rasta broja ne bi trebalo da bude problem. Međutim, osiguravanje da broj ne prelazi maxSnowflakes može biti korisno.
Rešenje: Proveravam trenutni broj ih trenutno u snowflakes nizu pre dodavanja nove pahuljke.
typescript
if (snowflakes.length < maxSnowflakes) {
snowflakes.push(createSnowflake(canvas.width, canvas.height));
}
Dodavanje width: "100%" i height: "100%" u Style za Canvas:
Problem: Bez ovih stilova, canvas može imati nepredviđene dimenzije u nekim slučajevima.
Rešenje: Dodao sam width: "100%" i height: "100%" kako bih osigurao da canvas pokriva celu prozor pregledača.