d3 / d3-color

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

Add a convenience method for hex color strings? #38

Closed songololo closed 6 years ago

songololo commented 6 years ago

Any possibility / support for adding a convenience method to return the colour in hex format?

mbostock commented 6 years ago

No immediate plans to support this, but here’s one implementation:

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

d3.rgb.prototype.toHexString = function() {
  return "#" + hex(this.r) + hex(this.g) + hex(this.b);
};
songololo commented 6 years ago

Thanks, extending the prototype works fine for my case.