From 5998d38878d600f57ba5df08f5b381538bf335e4 Mon Sep 17 00:00:00 2001 From: George Gkasdrogkas Date: Sun, 28 Jul 2019 21:29:01 +0300 Subject: [PATCH] feat(ColorToRGBA): support HSL format closes issue #505 --- src/Util.ts | 68 +++++++++++++++++++++++++++++++++++++++++- test/unit/Util-test.js | 23 ++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/src/Util.ts b/src/Util.ts index b86e54fa..21e0599c 100644 --- a/src/Util.ts +++ b/src/Util.ts @@ -697,7 +697,8 @@ export const Util = { Util._hex3ColorToRGBA(str) || Util._hex6ColorToRGBA(str) || Util._rgbColorToRGBA(str) || - Util._rgbaColorToRGBA(str) + Util._rgbaColorToRGBA(str) || + Util._hslColorToRGBA(str) ); }, // Parse named css color. Like "green" @@ -761,6 +762,71 @@ export const Util = { }; } }, + // Code adapted from https://github.com/Qix-/color-convert/blob/master/conversions.js#L244 + _hslColorToRGBA(str: string) { + // Check hsl() format + if (/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(str)) { + // Extract h, s, l + const [_, ...hsl]= /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(str); + + const h = Number(hsl[0]) / 360; + const s = Number(hsl[1]) / 100; + const l = Number(hsl[2]) / 100; + + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return { + r: Math.round(val), + g: Math.round(val), + b: Math.round(val), + a: 1 + }; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return { + r: Math.round(rgb[0]), + g: Math.round(rgb[1]), + b: Math.round(rgb[2]), + a: 1 + }; + } + }, /** * check intersection of two client rectangles * @method diff --git a/test/unit/Util-test.js b/test/unit/Util-test.js index adccc038..1072efd3 100644 --- a/test/unit/Util-test.js +++ b/test/unit/Util-test.js @@ -25,4 +25,27 @@ suite('Util', function() { } }); }); + + test('colorToRGBA() - from HSL to RGBA conversion', function() { + assert.deepEqual(Konva.Util.colorToRGBA('hsl(0, 0%, 0%)'), { + r: 0, + g: 0, + b: 0, + a: 1 + }); + + assert.deepEqual(Konva.Util.colorToRGBA('hsl(96, 48%, 59%)'), { + r: 140, + g: 201, + b: 100, + a: 1 + }); + + assert.deepEqual(Konva.Util.colorToRGBA('hsl(200, 100%, 70%)'), { + r: 102, + g: 204, + b: 255, + a: 1 + }); + }); });