Color Converter
Converted Colors:
RGB: ${rgb.r}, ${rgb.g}, ${rgb.b}
HSL: ${hsl.h}, ${hsl.s}%, ${hsl.l}%
`; } if (rgbInput) { const rgbArr = rgbInput.split(',').map(Number); const hex = rgbToHex(rgbArr[0], rgbArr[1], rgbArr[2]); const hsl = rgbToHsl(rgbArr[0], rgbArr[1], rgbArr[2]); output.innerHTML += `RGB: ${rgbInput}
HEX: ${hex}
HSL: ${hsl.h}, ${hsl.s}%, ${hsl.l}%
`; } if (hslInput) { const hslArr = hslInput.split(',').map((v, i) => i === 0 ? Number(v) : v.trim()); const rgb = hslToRgb(hslArr[0], parseFloat(hslArr[1]) / 100, parseFloat(hslArr[2]) / 100); const hex = rgbToHex(rgb.r, rgb.g, rgb.b); output.innerHTML += `HSL: ${hslInput}
RGB: ${rgb.r}, ${rgb.g}, ${rgb.b}
HEX: ${hex}
`; } }); function hexToRgb(hex) { let r = 0, g = 0, b = 0; // 3 digits if (hex.length === 4) { r = parseInt(hex[1] + hex[1], 16); g = parseInt(hex[2] + hex[2], 16); b = parseInt(hex[3] + hex[3], 16); } // 6 digits else if (hex.length === 7) { r = parseInt(hex[1] + hex[2], 16); g = parseInt(hex[3] + hex[4], 16); b = parseInt(hex[5] + hex[6], 16); } return { r, g, b }; } function rgbToHex(r, g, b) { return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase(); } function rgbToHsl(r, g, b) { r /= 255, g /= 255, b /= 255; let max = Math.max(r, g, b), min = Math.min(r, g, b); let h, s, l = (max + min) / 2; if (max === min) { h = s = 0; // achromatic } 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) }; } function hslToRgb(h, s, l) { let r, g, b; h /= 360; s /= 100; l /= 100; const k = (n) => (n + h * 12) % 12; const f = (n) => l - l * s * Math.max(0, Math.min(k(n), 1, 4 - k(n), 1)); r = Math.round(f(0) * 255); g = Math.round(f(8) * 255); b = Math.round(f(4) * 255); return { r, g, b }; }
No comments:
Post a Comment