Darky WC
Darky WC

Reputation: 311

Monochromatic color palette generation with d3 library

Is there a built in method to generate monochromatic colors with d3 library when given a color input?

I have search around but I find nothing.

The closest way I figure out now is:

  1. Convert the provided color into HSL format
  2. Pick up the saturation and save it as s1
  3. Find the minimum saturation by using s1-1 and save it as s2
  4. Interpolate s1 and s2 by 10 with d3
  5. Use the absolute value of the interpolated saturation to generate color palette by fixing (H)ue and (L)ight

Is there any efficient way to do this?

Upvotes: 3

Views: 632

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102219

There are several ways to achieve this. One of them is using a sequential scale.

For instance, given your provided colour (say, blue) in HSL format...

const color = d3.hsl("blue");

...all you need is:

const scale = d3.scaleSequential(t => d3.hsl(color.h, color.s * t, color.l) + "");

The value you'll pass to the interpolator goes from 0 to 1. As you can see, we'll multiply the saturation value by that number (color.s * t), so it will effectively go from 0 to its normal value.

Here is a demo creating a palette with 40 values:

const color = d3.hsl("blue");
const scale = d3.scaleSequential(t => d3.hsl(color.h, color.s * t, color.l) + "").domain([0, 40]);
d3.select("body")
  .selectAll(null)
  .data(d3.range(40))
  .enter()
  .append("div")
  .style("background-color", d => scale(d))
div {
  width: 10px;
  height: 50px;
  display: inline-block;
  margin-right: 2px;
}
<script src="https://d3js.org/d3.v6.min.js"></script>

Upvotes: 2

Related Questions