Reputation: 87
I,m new to D3.js and trying to understand gradient fill in D3.js. I,m following this tutorial
http://bl.ocks.org/mbostock/1086421
and its working like a charm.
I just need someone to explain me whats happening in this code here :
var gradient = svg.append("defs")
.append("linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "#0c0")
.attr("stop-opacity", 1);
gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", "#c00")
.attr("stop-opacity", 1);
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "url(#gradient)");
From what i understand is that we are defining our gradient using the def tag. but i need to understand what the hell is going on in the rest of lines.
1)- What is appending this tag "linearGradient" has to do. Is that a valid html tag or can we create some other tag?
2)- What is speadMethod, "pad" doing ? What kind of attr is that ?
3)- Finally what is offset here ? what is stop-color and stop-opacity ?
An explanation in simple terms would be awesome so that i can change the color opacity according to my needs.
Upvotes: 0
Views: 1520
Reputation: 2751
All of the code is performing work on a pre-existing <svg>
element. The first statement adds a <defs>
element to the svg element (see more here), and the subsequent gradient.append
statements add specifics for a linear gradient, identified by #gradient
which can be reused. The last statement creates a <rect>
svg element and applies the #gradient
def to it, utilizing this newly-created linear gradient definition.
Upvotes: 1