Linear gradients automized in d3

Camelia D. Brumar
2 min readJan 27, 2021

I always have to spend time crafting functions that create HTML programmatically. If you are looking for how to create a linear gradient in d3 with an arbitrary number of colors and any rotation angle, here you go.

This is how it would look like in HTML:

The defs tag is very useful in this case, and what it does is store graphical elements in it to be used at a later time. In our case, we store the lienarGradient tag we would like to use later to fill a rectangle. The result looks like this:

We use gradientTransform attribute is used to rotate the direction of the linear gradient, if you play a bit with the number in the rotate() function you will get the gist of it. Then, inside the lienarGradient tag, we have multiple stop tags, which specify where a certain color stops and where the next one starts, assuming that the first color goes from position 0.

Finally, I create a rectangle with the rect tag and we use the id of the linear gradient we’ve just created before as the fill of the rectangle as follows: fill=”url(‘#myGradient’)”.

The d3 code that creates the gradient automatically given any list of colors can be found below:

This function takes as parameters a list of colors of arbitrary size, and the rotation angle. See the comments in the code above for the details on the implementation.

Below you can find the HTML where it is illustrated how to use this function. I hope it helps!

--

--

Camelia D. Brumar

Ph.D. Candidate in Computer Science at Tufts University working with Dr. Remco Chang in the Visual Analytics Lab ([v]alt).