How to draw a circle with gradient color? Say, a gradient from yellow to blue.
Normally, to create a circle in yellow we can use the following code:
var
You have to define the gradient in the SVG first, and then fill the circle with an SVG link to the gradient element.
// Define the gradient
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
// Define the gradient colors
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#a00000")
.attr("stop-opacity", 1);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#aaaa00")
.attr("stop-opacity", 1);
// Fill the circle with the gradient
var circle = svg.append('circle')
.attr('cx', width / 2)
.attr('cy', height / 2)
.attr('r', height / 3)
.attr('fill', 'url(#gradient)');
A jsFiddle with the complete example. More details on how to define SVG gradients in the MDN Tutorial. The resulting image: