SVG Adding radial gradient to donut chart

北城余情 提交于 2019-12-18 16:57:37

问题


I'm drawing charts with d3.js.
Is it possible to add radial gradients to donut chart, how on this picture?


回答1:


Assuming the arc parts are path elements that are filled you can use a radial gradient to get that result.

See this similar question, we can reuse the example to arrive at:

var dataset = {
  apples: [53245, 28479, 19697, 24037, 40245],
};

var width = 460,
    height = 300,
    radius = Math.min(width, height) / 2;

var color = d3.scale.category20();

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc()
    .innerRadius(radius - 100)
    .outerRadius(radius - 50);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var grads = svg.append("defs").selectAll("radialGradient").data(pie(dataset.apples))
    .enter().append("radialGradient")
    .attr("gradientUnits", "userSpaceOnUse")
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", "100%")
    .attr("id", function(d, i) { return "grad" + i; });
grads.append("stop").attr("offset", "15%").style("stop-color", function(d, i) { return color(i); });
grads.append("stop").attr("offset", "20%").style("stop-color", "white");
grads.append("stop").attr("offset", "27%").style("stop-color", function(d, i) { return color(i); });

var path = svg.selectAll("path")
    .data(pie(dataset.apples))
  .enter().append("path")
    .attr("fill", function(d, i) { return "url(#grad" + i + ")"; })
    .attr("d", arc);

Jsfiddle: http://jsfiddle.net/X8hfm/



来源:https://stackoverflow.com/questions/21828315/svg-adding-radial-gradient-to-donut-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!