When drawing lines or areas, we usually want to color them depending on the value they represent.
D3js provides (of course) an easy way to create color scales, called d3-scale-chromatic. Many color scales are already created, and accessing to their colors is easy:
- Just choose the color scale function from the docs
- There are sequential, diverging and categorical color schemes. The last ones are just an array
- Call the function passing a value from 0 to 1 to get the color in all the domain
- To calculate this value from 0 to 1 given the actual value, just call a d3.scaleSequential function, and don’t forget to clamp it
- Create an object with the scale definitions (the source code has many of them already done)
- Create a small hidden canvas with 255 columns and one line. Each column will represent a scale value, and could be larger for a smoother gradient
- Create a gradient for each change in the color scale
- When the hidden canvas is created, get its data and query it to get the colours
The code is:
The resulting color scale, that you can see if the .style(“display”,”none”) is removed, is:
- The color scale definition cs_def takes the colors and the position of each color in the scale from 0 to 1.
- The scale is created 256 pixels width and 1 height, to act as an array with the colors. The width could be higher.
- createLinearGradient will create the color gradient and gradient.addColorStop will add a color change at each position
- The getImageData().data method returns an array with all the colors. The size will be 256 * 4, since it holds the RGBA values
The color for each value is calculated using this code:
- The fisrt line calculates the position from 0 to 255. domain is the minimum value, and domain the maximum
- The alpha part is necessary to avoid strange colors if the value is below or above the extremes of the scale. It will set the transparency to 100%
- csImageData has all the colours, ocupying four positions each.
- The alpha value could be read and set the same way
- Usually, this chunk of code will be inside a loop to set all the pixels, as you can see in the drawing raster data section