2017-03-03 60 views
0

以下是我的代码。我做了一个圆,圆弧5,现在我要添加文本到各电弧使得:http://bl.ocks.org/nbremer/raw/b603c3e0f7a74794da87/如何在D3.js中的每个弧上包装文本?

// declarations 
const svgSize = { 
    width: 1000, 
    height: 800 
}; 

// setup 
let svg = d3 
    .select('body') 
    .append('svg') 
    .attr('width', svgSize.width) 
    .attr('height', svgSize.height) 
    .append('g') 
    .attr('transform', 'translate(' + svgSize.width/2 + ',' + svgSize.height/2 + ')'); 

// drawing 
let arcGenerator = d3.arc() 
    .innerRadius(296) 
    .outerRadius(300); 

let arcData = [ 
    { startAngle: 0, endAngle: 0.2 }, 
    { startAngle: 0.2, endAngle: 0.6 }, 
    { startAngle: 0.6, endAngle: 1.4 }, 
    { startAngle: 1.4, endAngle: 3 }, 
    { startAngle: 3, endAngle: 2 * Math.PI } 
]; 

d3.select('g') 
    .selectAll('path') 
    .data(arcData) 
    .enter() 
    .append('path') 
    .attr('d', arcGenerator); 
+3

该代码被写了Nadieh布雷默。如果你看她的博客,你会看到她有一个完整的帖子,一步一步地解释如何去做:https://www.visualcinnamon.com/2015/09/placing-text-on-arcs .html。这几乎可以回答这个问题。 –

回答

0
d3.select('g') 
    .selectAll('path') 
    .data(arcData) 
    .enter() 
    .append('path') 
    .attr("id", (d, i) => { return "uniqueId_" + i; }) 
    .attr('d', arcGenerator); 

let monthData = [{ month: 'Jan' }, { month: 'Feb' }, { month: 'Mar' }, { month: 'Apr' }, { month: 'May' },] 

// append the month names to each slice 
svg.selectAll(".monthText") 
    .data(monthData) 
    .enter().append("text") 
    .attr("class", "monthText") 
    .attr("x", 10) // move the text from the start angle of the arc 
    .attr("dy", -10) // move the text down 
    .append("textPath") 
    .attr("xlink:href", function (d, i) { return "#uniqueId_" + i; }) 
    .text(function (d) { return d.month; });