SVG线条超出弧形起始位置 - d3.js

4

我正在尝试实现这个 enter image description here

但目前我只能做到这个程度 enter image description here 本质上,我只需要找出如何让从圆形发出的线条从弧的起点开始。

我的问题也正是如此,我该如何将弧的起始位置转换为svg线条的x1、y1属性。以下是我目前涉及绘制线条的代码:

// Draw lines emanating out
g.append('line')
    .attr('class', 'outer-line')
    .attr('x1', function(d) {
        return 0;
    })
    .attr('x2', 0)
    .attr('y1', -radius)
    .attr('y2', -radius-150)
    .attr('stroke', function(d, i) {
        return color(i); 
    })
    .attr('stroke-width','2')
    .attr("transform", function(d) {
        return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
    });

不能让这些线条从中心点出来吗? - ksav
1个回答

4
如果我正确理解您的问题,您只需要使用d.startAngle
g.attr("transform", function(d) {
    return "rotate(" + d.startAngle * (180/Math.PI) + ")";
});

点击“运行代码片段”以查看示例:

var dataset = [300, 200, 400, 200, 300, 100, 50];

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 path = svg.selectAll("path")
    .data(pie(dataset))
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);
    
var g = svg.selectAll(".groups")
  .data(pie(dataset))
  .enter()
  .append("g");
  
  g.append('line')
    .attr('class', 'outer-line')
    .attr('x1', 0)
    .attr('x2', 0)
    .attr('y1', -radius + 50)
    .attr('y2', -radius)
    .attr('stroke', 'black')
    .attr('stroke-width','2')
    .attr("transform", function(d) {
        return "rotate(" + d.startAngle * (180/Math.PI) + ")";
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


3
太准确了!我应该意识到是变换属性在决定弧线位置,谢谢! - Joey Orlando

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接