From 27a2bb353a20be869ae6de3725f9cbd265962499 Mon Sep 17 00:00:00 2001 From: Gregor Aisch Date: Sun, 13 Oct 2024 12:16:55 +0200 Subject: [PATCH] fix: hue-less interpolation in lch, resolves #359 --- src/io/lch/hcl2rgb.js | 4 ++-- src/io/lch/index.js | 4 ++-- src/utils/index.js | 12 +++++++++++- test/mix.test.js | 12 ++++++++++++ 4 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/io/lch/hcl2rgb.js b/src/io/lch/hcl2rgb.js index 3b42ab61..5d8c8ae7 100644 --- a/src/io/lch/hcl2rgb.js +++ b/src/io/lch/hcl2rgb.js @@ -1,8 +1,8 @@ -import { unpack } from '../../utils/index.js'; +import { unpack, reverse3 } from '../../utils/index.js'; import lch2rgb from './lch2rgb.js'; const hcl2rgb = (...args) => { - const hcl = unpack(args, 'hcl').reverse(); + const hcl = reverse3(unpack(args, 'hcl')); return lch2rgb(...hcl); }; diff --git a/src/io/lch/index.js b/src/io/lch/index.js index 04dc2ad5..d472ef33 100644 --- a/src/io/lch/index.js +++ b/src/io/lch/index.js @@ -1,4 +1,4 @@ -import { unpack, type } from '../../utils/index.js'; +import { unpack, type, reverse3 } from '../../utils/index.js'; import chroma from '../../chroma.js'; import Color from '../../Color.js'; import input from '../input.js'; @@ -10,7 +10,7 @@ Color.prototype.lch = function () { return rgb2lch(this._rgb); }; Color.prototype.hcl = function () { - return rgb2lch(this._rgb).reverse(); + return reverse3(rgb2lch(this._rgb)); }; const lch = (...args) => new Color(...args, 'lch'); diff --git a/src/utils/index.js b/src/utils/index.js index 4f050845..2dcf13bc 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -14,4 +14,14 @@ const PITHIRD = PI / 3; const DEG2RAD = PI / 180; const RAD2DEG = 180 / PI; -export { PI, TWOPI, PITHIRD, DEG2RAD, RAD2DEG, min, max, rnd2, rnd3 }; +/** + * Reverse the first three elements of an array + * + * @param {any[]} arr + * @returns {any[]} + */ +function reverse3(arr) { + return [...arr.slice(0, 3).toReversed(), ...arr.slice(3)]; +} + +export { PI, TWOPI, PITHIRD, DEG2RAD, RAD2DEG, min, max, rnd2, rnd3, reverse3 }; diff --git a/test/mix.test.js b/test/mix.test.js index a5abe4dc..e0253b3a 100644 --- a/test/mix.test.js +++ b/test/mix.test.js @@ -88,4 +88,16 @@ describe('Some tests for chroma.color()', () => { const result = chroma.interpolate('red', 'blue', 0.5, 'lrgb'); expect(result.hex()).toBe('#b400b4'); }); + + it('mix gray and black', () => { + const result = chroma.mix('#666666', '#000000', 0.5, 'lch'); + expect(result.hex()).toBe('#343434'); + expect(result.css()).toBe('rgb(52 52 52)'); + }); + + it('mix transparent gray and black', () => { + const result = chroma.mix('#66666600', '#000000', 0.5, 'lch'); + expect(result.hex()).toBe('#34343480'); + expect(result.css()).toBe('rgb(52 52 52 / 0.5)'); + }); });