Draw a D3 circle with gradient colours

后端 未结 2 951
面向向阳花
面向向阳花 2021-02-13 09:43

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          


        
2条回答
  •  死守一世寂寞
    2021-02-13 10:24

    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

提交回复
热议问题