Skip to content

Commit

Permalink
[css-color-4] Avoid returning negative saturation in rgb to hsl conve…
Browse files Browse the repository at this point in the history
…rsion, #9222
  • Loading branch information
svgeesus committed Dec 16, 2023
1 parent a9a8922 commit 905e7cd
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
6 changes: 5 additions & 1 deletion css-color-4/Overview.bs
Original file line number Diff line number Diff line change
Expand Up @@ -2261,8 +2261,12 @@ Converting sRGB Colors to HSL</h3>

Conversion in the reverse direction proceeds similarly.

Special care is taken to deal with
intermediate negative values of saturation,
which can be produced by colors far outside the sRGB gamut.

<pre class="include-code lang-javascript">
path: rgbToHsl.js
path: better-rgbToHsl.js
highlight: js
</pre>

Expand Down
40 changes: 40 additions & 0 deletions css-color-4/better-rgbToHsl.js
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];
}

0 comments on commit 905e7cd

Please sign in to comment.