Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a D3 circle with gradient colours

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 cdata=[50,40];
var xscale=40;
var xspace =50;
var yscale=70;

var svg = d3.select("body")
    .append("svg")
    .attr("width", 1600)
    .attr("height", 1600);

var circle = svg.selectAll("circle")
    .data(cdata)
   .enter()
    .append("circle");

var circleattr = circle
    .attr("cx", function(d) {
        xscale = xscale+xspace;
        return xscale;
    })
    .attr("cy", function(d) {
        yscale=yscale+xspace+10;
        return yscale;
    })
    .attr("r", function(d) {
        return d;
    })
    .style("fill","yellow");
like image 511
user2637905 Avatar asked Dec 30 '13 09:12

user2637905


1 Answers

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:

Circle with gradient, created in D3

like image 193
Pablo Navarro Avatar answered Oct 17 '22 07:10

Pablo Navarro