-
-
Notifications
You must be signed in to change notification settings - Fork 69
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adapts the implementation given in https://drafts.csswg.org/css-color/#hsl-to-rgb. Fixes #142.
- Loading branch information
Showing
2 changed files
with
21 additions
and
16 deletions.
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 |
---|---|---|
@@ -1,21 +1,19 @@ | ||
'use strict'; | ||
|
||
const hueToRgb = (t1, t2, hue) => { | ||
if (hue < 0) hue += 6; | ||
if (hue >= 6) hue -= 6; | ||
|
||
if (hue < 1) return (t2 - t1) * hue + t1; | ||
else if (hue < 3) return t2; | ||
else if (hue < 4) return (t2 - t1) * (4 - hue) + t1; | ||
else return t1; | ||
}; | ||
const MAX_HUE = 360; | ||
const COLOR_NB = 12; | ||
const MAX_RGB_VALUE = 255; | ||
|
||
// https://www.w3.org/TR/css-color-4/#hsl-to-rgb | ||
exports.hslToRgb = (hue, sat, light) => { | ||
const t2 = light <= 0.5 ? light * (sat + 1) : light + sat - light * sat; | ||
const t1 = light * 2 - t2; | ||
const r = hueToRgb(t1, t2, hue + 2); | ||
const g = hueToRgb(t1, t2, hue); | ||
const b = hueToRgb(t1, t2, hue - 2); | ||
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; | ||
hue = hue % MAX_HUE; | ||
if (hue < 0) { | ||
hue += MAX_HUE; | ||
} | ||
function f(n) { | ||
const k = (n + hue / (MAX_HUE / COLOR_NB)) % COLOR_NB; | ||
const a = sat * Math.min(light, 1 - light); | ||
return light - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); | ||
} | ||
return [f(0), f(8), f(4)].map(value => Math.round(value * MAX_RGB_VALUE)); | ||
Check warning on line 18 in lib/utils/colorSpace.js GitHub Actions / Lint and tests (18)
Check warning on line 18 in lib/utils/colorSpace.js GitHub Actions / Lint and tests (20)
|
||
}; |