Reputation: 3082
I'm unclear about how HSL colours are meant to be written. W3 has them like this:
color: hsl(120, 100%, 50%);
Whereas ThreeJs asks for them like this:
h — hue value between 0.0 and 1.0
s — saturation value between 0.0 and 1.0
l — lightness value between 0.0 and 1.0
I've seen HSL colours written both ways across the web and really don't get it - which is correct, and how do you convert between the two?
Cheers.
Upvotes: 0
Views: 1647
Reputation: 2830
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:
function parseHsl(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) {
throw new Error('Not an HSL color.');
}
var h = +match[1];
var s = +match[2];
var l = +match[3];
if (isNaN(h) || isNaN(s) || isNaN(l)) {
throw new Error('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) {
throw new Error('Out of range.');
}
return {
h: h,
s: s,
l: l
};
}
function getCssHslColor(hsl) {
return 'hsl(' + hsl.h * 360 + ',' + hsl.s * 100 + '%,' + hsl.l * 100 + '%)';
}
Upvotes: 0
Reputation: 96737
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:
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>
Upvotes: 1