Skip to content
mbostock edited this page May 30, 2011 · 19 revisions

API Reference

Constructing visualizations often involves working with colors. Even though your browser understands a lot about colors, it doesn't offer much help in manipulating colors through JavaScript. So D3 provides representations for both RGB and HSL colors, allowing interpolation in both color spaces, and making colors brighter or darker. For more about color manipulation, see the Wikipedia entries on RGB and HSL.

Note: while you can work with colors directly, you might also want to take a look at D3's built-in interpolateRgb, interpolateHsl and scales. There are also some fantastic categorical color scales built-in to D3 provided by ColorBrewer.

RGB

# d3.rgb(r, g, b)

Constructs a new RGB color with the specified r, g and b channel values. Each channel must be specified as an integer in the range [0,255]. The channels are available as the r, g and b attributes of the returned object.

# d3.rgb(color)

Constructs a new RGB color by parsing the specified color string. If color is not a string, it is coerced to a string; thus, this constructor can also be used to create a copy of an existing color, or force the conversion of a d3.hsl color to RGB. The color string may be in a variety of formats:

  • rgb decimal - "rgb(255,255,255)"
  • hsl decimal - "hsl(120,50%,20%)"
  • rgb hexadecimal - "#ffeeaa"
  • rgb shorthand hexadecimal - "#fea"
  • named - "red", "white", "blue"

The resulting color is stored as red, green and blue integer channel values in the range [0,255]. The channels are available as the r, g and b attributes of the returned object. The list of supported named colors is specified by CSS.

# rgb.brighter([k])

Returns a brighter copy of this color. Each channel is multiplied by 0.7 ^ -k. The the gamma value k is omitted, it defaults to 1. Channel values are capped at the maximum value of 255, and the minimum value of 30.

# rgb.darker([k])

Returns a darker copy of this color. Each channel is multiplied by 0.7 ^ k. The the gamma value k is omitted, it defaults to 1.

# rgb.hsl()

Returns the equivalent color in HSL space.

# rgb.toString()

Converts this RGB color to a string, such as "#f7eaba".

HSL

# d3.hsl(h, s, l)

# d3.hsl(color)

# hsl.brighter([k])

# hsl.darker([k])

# hsl.rgb()

# hsl.toString()

Clone this wiki locally