Aligning text inside circular arc d3js

2019-03-22 04:24发布

I'm trying to draw a chart with concentric circles where the radius will define the distance between various points. I want the labels for all points at a particular distance to appear inside the respective shell. I'm using d3 to draw the graph. I have everything going except I can't figure out how to ensure that the text renders nicely and aligned to a baseline with constant character width and character spacing. I have spent a whole day trying to figure it out and any help will be greatly appreciated.

Here's the JSFiddle

here is the javascript code

var dataset = [{label:"Hello1", value:5},{label:"Hello2", value:10 {label:"Hello3",value:15},{label:"Hello4", value:20},{label:"Hello5", value:25}];

var arc = d3.svg.arc()
  .innerRadius(function(d,i){return i*35;})
  .outerRadius(function(d,i){return (i*35+30);})
  .startAngle(0)
  .endAngle(2 * Math.PI);

var svg = d3.select("body").append("svg")
  .attr("width", 960)
  .attr("height", 500)
  .selectAll("g")
  .data(dataset)
  .enter()
  .append("g")
  .attr("transform", "translate(480,250)");

var arcs = svg.append("path")
  .attr("fill","red")
  .attr("id", function(d,i){return "s"+i;})
  .attr("d",arc);

var thing = svg.append("g")
  .attr("id","thing")
  .style("fill","navy");

thing.append("text")
  .style("font-size",20)
  .attr("dy",function(d,i){return 20;})
  //.attr("alignment-baseline","middle")
  .append("textPath")
  .attr("textLength",function(d,i){return 90-i*5 ;})
  .attr("xlink:href",function(d,i){return "#s"+i;})
  .attr("startOffset",function(d,i){return 3/20;})
  .text(function(d){return d.label;})

标签: svg d3.js
1条回答
劫难
2楼-- · 2019-03-22 05:05

Do you mean something like this:

http://jsfiddle.net/wcWUE/

All I changed was:

thing.append("text")
  .style("font-size",20)
  .append("textPath")
  .attr("textLength",function(d,i){return 90-i*5 ;})
  .attr("xlink:href",function(d,i){return "#s"+i;})
  .attr("startOffset",function(d,i){return 3/20;})
  .attr("dy","-1em")
  .text(function(d){return d.label;})

Also I reversed the order of the rings so that occlusion was not a problem.

I think you could make a separate collection of paths possibly just defined in a section to draw the text along.

But I'm not sure if this result is what you are looking for?

查看更多
登录 后发表回答