thi-ng / umbrella

⛱ Broadly scoped ecosystem & mono-repository of 199 TypeScript projects (and ~180 examples) for general purpose, functional, data driven development
https://thi.ng
Apache License 2.0
3.35k stars 149 forks source link

The mix() function in @thi.ng/color modifies the input color #405

Closed AshishKrGoya1 closed 1 year ago

AshishKrGoya1 commented 1 year ago

After employing the mix() function in @thi.ng/color to manually interpolate colors, I noticed that the original input color has undergone a transformation.

import { hsv, mix } from "@thi.ng/color";

  const col1 = hsv(0, 0.0, 1);
  const col2 = hsv(0.4, 1, 1);

  const num = 4;

  console.log(col1.buf); // [0, 0, 1, 1]
  for (let i = 0; i < num; i++) {
    // use null
    const colMid = mix(null, col1, col2, i / (num - 1));
  }
  console.log(col1.buf); // [0.4, 1, 1, 1] - it should be [0, 0, 1, 1]

Looks to be good when i try to reuse the same. Is there anything which i can change here.

let colMid = hsv();
  console.log(col1.buf); // [0, 0, 1, 1]
  for (let i = 0; i < num; i++) {
    // reuse
    mix(colMid, col1, col2, i / (num - 1));
  }
  console.log(col1.buf); // [0, 0, 1, 1] correct value

Thank you in advance !!

postspectacular commented 1 year ago

This is actually expected and documented behavior: When the first argument is null, this function (and others) will mutate the 2nd arg, thus allowing the same functions to control where results should be written to and to be used for both in-place manipulation or immutable ops. Also see remarks in the mix() documentation.

This same convention also applies to (and stems from) most of the 900+ vector & matrix operations in the thi.ng/vectors & thi.ng/matrices packages. You can find more examples in those readme & docs too.

If you want to create a number of new, independent color objects for your mix results, then the following would work (use of transducers package is optional, but useful):

import { map, normRange } from "@thi.ng/transducers"

const gradient = [...map((t) => mix(hsv(), col1, col2, t), normRange(4))];

gradient.map((x) => css(x))
// [
//   'hsl(0.000,0.000%,100.000%)',
//   'hsl(36.000,100.000%,87.500%)',
//   'hsl(72.000,100.000%,75.000%)',
//   'hsl(108.000,100.000%,62.500%)',
//   'hsl(144.000,100.000%,50.000%)'
// ]

If you don't know the color type/space of the input colors, you can derive a new matching color object from one of the inputs, e.g. mix(col1.empty(), col1, col2, 0.5) or mix(col1.copy(), ...)

kumarashish2405 commented 1 year ago

@postspectacular i agree and see that in updated docs. Thanks