"use client"; import { useState, useEffect } from "react"; import { Palette, Copy, RefreshCw } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Label } from "@/components/ui/label"; import { toast } from "sonner"; export default function ColorPickerPage() { const [color, setColor] = useState("#4F46E5"); const [formats, setFormats] = useState({ hex: "#4F46E5", rgb: "rgb(79, 70, 229)", hsl: "hsl(243, 75%, 59%)" }); const hexToRgb = (hex: string) => { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }; const rgbToHsl = (r: number, g: number, b: number) => { r /= 255; g /= 255; b /= 255; const max = Math.max(r, g, b), min = Math.min(r, g, b); let h = 0, s, l = (max + min) / 2; if (max === min) { h = s = 0; } else { const d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) }; }; useEffect(() => { const rgb = hexToRgb(color); if (rgb) { const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b); setFormats({ hex: color.toUpperCase(), rgb: `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`, hsl: `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)` }); } }, [color]); const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text); toast.success(`已复制: ${text}`); }; const randomColor = () => { const randomHex = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0'); setColor(randomHex.toUpperCase()); }; return (
HEX、RGB、HSL 颜色格式互转