d3 / d3-color

Color spaces! RGB, HSL, Cubehelix, CIELAB, and more.
https://d3js.org/d3-color
ISC License
401 stars 91 forks source link

Replace clamping with validation for RGB values #10

Closed devgru closed 9 years ago

devgru commented 9 years ago

README says:

Colors are now validated upon construction.

In fact they are clamped, not validated.

IMHO clamping isn't a good idea for RGB constructor, it hides "invalid" LAB/HCL colors instead of notifying about them. Would you mind throwing exception or returning special value for invalid colors?

It is the only way to check whether LAB/HCL color is "valid" or not.

I'm using this kind of validation here: https://github.com/devgru/postcss-color-hcl/blob/master/index.js#L22

mbostock commented 9 years ago

Added color.displayable; fixed in 0.2.2.

devgru commented 9 years ago

Superb, thanks!

mbostock commented 9 years ago

Also as heads-up since I peeked at your code: in 0.2.3, I no longer force RGB channel values to be integers. (This avoids quantization when converting between color spaces, though note that rgb.toString still rounds internally.) So, if you want to format your own color string, such as to make a CSS rgba color, you’ll want to do rounding—and possibly clamping—yourself. For example:

var c = color.rgb(…);
console.log("rgba("
    + Math.max(0, Math.min(255, Math.round(c.r))) + ","
    + Math.max(0, Math.min(255, Math.round(c.g))) + ","
    + Math.max(0, Math.min(255, Math.round(c.b))) + ","
    + α + ")");