Reputation: 311
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:
s1
s1-1
and save it as s2
s1
and s2
by 10 with d3Is there any efficient way to do this?
Upvotes: 3
Views: 632
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