JavaScript: HSL to RGB Converter
Trasnsform HSL Colors to RGB
Converting from HSL (Hue, Saturation, Lightness) color values back into the standard RGB format effortlessly with this JavaScript function.
Essential for workflows that involve manipulating colors in the HSL space and then needing to represent them in RGB for display or other uses.
π― Key Features:
-
Flexible Input: Accepts HSL colors as arrays
[h, s, l]
, objects{h, s, l}
, and various string formats like"hsl(h, s, l)"
,"(h, s, l)"
, or"h, s, l"
. - Percentage Support: Handles Saturation and Lightness values whether they are in the 0-1 range or 0-100 (percentages).
- Accurate Conversion: Provides precise conversion from HSL to RGB color space.
How It Works
The function intelligently detects whether the input is an array, an object, or a string. If itβs a string, it parses the hue, saturation, and lightness components from the various supported formats, including handling percentage signs. It then normalizes the H, S, and L values to the ranges expected by the conversion algorithm (H to 0-1, S and L to 0-1). Using standard color space formulas, it calculates the corresponding Red, Green, and Blue components. These values are then converted back to the 0-255 range and returned as an RGB object { r, g, b }
.
Example Usage:
// Using an array input (S and L in 0-1 range)
const rgbFromArr = hslToRgb([0, 1, 0.5]);
console.log(rgbFromArr); // Output: { r: 255, g: 0, b: 0 }
// Using an object input (S and L in 0-1 range)
const rgbFromObj = hslToRgb({ h: 120, s: 1, l: 0.5 });
console.log(rgbFromObj); // Output: { r: 0, g: 255, b: 0 }
// Using 'hsl()' string format (S and L in %)
const rgbFromHslString = hslToRgb("hsl(240, 100%, 50%)");
console.log(rgbFromHslString); // Output: { r: 0, g: 0, b: 255 }
Ideal For:
- π¨ Integrating with color pickers that output HSL.
- βοΈ Applying color adjustments made in HSL back to RGB.
- π Displaying colors in RGB after generating them in HSL space.
- π» Any project needing robust HSL to RGB color space conversion.
Get Started with your Conversions!
A versatile JavaScript function designed to effortlessly convert your HSL color values into the RGB format.