d3/d3-interpolate

interpolateRgb("invalid", "red")(1) returns black

mbostock opened this issue · 2 comments

When interpolating from an invalid RGB color, we should assume the (potentially) valid channel values from the target color, rather than always returning black. This should apply to other color spaces, too.

  • rgb.r
  • rgb.g
  • rgb.b
  • hsl.h
  • hsl.s
  • hsl.l
  • hcl.h
  • hcl.c
  • hcl.l
  • lab.l
  • lab.a
  • lab.b
  • cubehelix.h
  • cubehelix.c
  • cubehelix.l

Okay, it’s slightly more complicated. In some color spaces, valid colors have NaN channel values. For example, hsl("black") is a valid color but does not have a defined hue or saturation, so the h and s channels are NaN; for hsl("gray"), s is 0 and h is NaN. In other color spaces, such as RGB, valid colors always have numeric channel values; only an invalid color has NaN channel values.

In color spaces that expect NaN channel values, you want bidirectional inheritance for interpolation. For example, when interpolating from black to red or red to black in HSL color space, you should use a constant hue of 0°.

On the other hand, in RGB space, if the start color is red and the end color is rgb(NaN, NaN, NaN), it doesn’t make sense to treat the end color as red. If you were to just set the end color directly, it would be treated as black, not red. So the end color should be treated as black.

The point is, in some color spaces colors are uniquely defined; in others, there are multiple representations. Only in the latter case is it valid to substitute an invalid end color channel value using the corresponding channel from the start color; however, in all color spaces it is valid to substitute an invalid start channel value with the corresponding end channel value.

It’s actually slightly more complicated now that we have opacity: when an RGB color is transparent, it is rgb(NaN, NaN, NaN, 0). So, this is a valid color, and if it’s the end value for interpolation, those end channel values should be substituted with the start channel values.

So… I think it might be best to always use bidirectional substitution.