-
Notifications
You must be signed in to change notification settings - Fork 688
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[css-color-4] Avoid returning negative saturation in rgb to hsl conve…
…rsion, #9222
- Loading branch information
Showing
2 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* @param {number} red - Red component 0..1 | ||
* @param {number} green - Green component 0..1 | ||
* @param {number} blue - Blue component 0..1 | ||
* @return {number[]} Array of HSL values: Hue as degrees 0..360, Saturation and Lightness in reference range [0,100] | ||
*/ | ||
function rgbToHsl (red, green, blue) { | ||
let max = Math.max(red, green, blue); | ||
let min = Math.min(red, green, blue); | ||
let [hue, sat, light] = [NaN, 0, (min + max)/2]; | ||
let d = max - min; | ||
|
||
if (d !== 0) { | ||
sat = (light === 0 || light === 1) | ||
? 0 | ||
: (max - light) / Math.min(light, 1 - light); | ||
|
||
switch (max) { | ||
case red: hue = (green - blue) / d + (green < blue ? 6 : 0); break; | ||
case green: hue = (blue - red) / d + 2; break; | ||
case blue: hue = (red - green) / d + 4; | ||
} | ||
|
||
hue = hue * 60; | ||
} | ||
|
||
// Very out of gamut colors can produce negative saturation | ||
// If so, just rotate the hue by 180 and use a positive saturation | ||
// see https://github.com/w3c/csswg-drafts/issues/9222 | ||
if (sat < 0) { | ||
hue += 180; | ||
sat = Math.abs(sat); | ||
} | ||
|
||
if (hue >= 360) { | ||
hue -= 360; | ||
} | ||
|
||
return [hue, sat * 100, light * 100]; | ||
} |