How Exactly Are Hsl Colours Meant To Be Written?
Solution 1:
For CSS, the W3C Recommendation CSS Color Module Level 3 defines how HSL color values have to be specified in the color
property:
HSL colors are encoding as a triple (hue, saturation, lightness). Hue is represented as an angle of the color circle (i.e. the rainbow represented in a circle). This angle is so typically measured in degrees that the unit is implicit in CSS; syntactically, only a is given. […] Saturation and lightness are represented as percentages.
tl;dr:
- hue: unitless
- saturation: percentage
- lightness: percentage
The next version, CSS Color Module Level 4 (which is currently only an Editor’s Draft) specifies this better (and it seems that the hue argument can have more values):
HSL colors are specified as a triplet of hue, saturation, and lightness. The syntax of the
hsl()
function is:hsl() = hsl( <hue>, <percentage>, <percentage> ) hsla() = hsla( <hue>, <percentage>, <percentage>, <alpha-value> ) <hue> = <number> | <angle> | <named-hue>
Solution 2:
For CSS hue value must be between 0 and 360 degrees, saturation and lightness must be between 0 and 100 percents, alpha channel must be between 0 and 1. You may use Regular Expressions to parse string CSS color and get the numeric values:
functionparseHsl(color) {
var hslRegexp = /^\s*hsl\s*\(\s*(\d{1,3}\.?\d?)\s*,\s*(\d{1,3}\.?\d*)%\s*,\s*(\d{1,3}\.?\d*)%\s*\)\s*$/var match = color.match(hslRegexp);
if (!match) {
thrownewError('Not an HSL color.');
}
var h = +match[1];
var s = +match[2];
var l = +match[3];
if (isNaN(h) || isNaN(s) || isNaN(l)) {
thrownewError('Not a number.');
}
h = h / 360;
s = s / 100;
l = l / 100;
if (h < 0 || h > 1 || s < 0 || s > 1 || l < 0 || l > 1) {
thrownewError('Out of range.');
}
return {
h: h,
s: s,
l: l
};
}
functiongetCssHslColor(hsl) {
return'hsl(' + hsl.h * 360 + ',' + hsl.s * 100 + '%,' + hsl.l * 100 + '%)';
}
Post a Comment for "How Exactly Are Hsl Colours Meant To Be Written?"