如何在Arc的末尾添加文本

时间:2018-03-20 11:18:25

标签: javascript html d3.js

请在下面找到我创建弧的代码,我想在圆弧末端的圆圈中附加文字(即结束角度)



var svgContainer = d3.select("body").append("svg")
  .append("svg:svg")
  .attr("width", 350)
  .attr("height", 350)
  .append("g")
  .attr("transform", "translate(50, 50)");

var outerRadius = 40;
var stroke = 5;

var outerArc = d3.arc()
  .innerRadius(outerRadius)
  .outerRadius(outerRadius)
  .startAngle(0)
  .endAngle(5);

svgContainer.append("path")
  .style("fill", "none")
  .style("stroke", "#0B9B29")
  .style("stroke-width", stroke)
  .attr('stroke-linejoin', 'round')
  .attr("d", outerArc());

<head>
  <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
&#13;
&#13;
&#13;

例如

enter image description here

1 个答案:

答案 0 :(得分:4)

在不处理电弧发生器本身的情况下,获取电弧终点的一种简单方法是使用getPointAtLength

var point = path.node().getPointAtLength(path.node().getTotalLength() / 2);

注意除以2:这是必要的,因为弧线到达结束角度然后回到开始。

然后,只需使用该点的xy属性绘制圆圈和文字。

以下是包含这些更改的代码:

&#13;
&#13;
var svgContainer = d3.select("body").append("svg")
  .append("svg:svg")
  .attr("width", 350)
  .attr("height", 350)
  .append("g")
  .attr("transform", "translate(50, 50)");

var outerRadius = 40;
var stroke = 5;

var outerArc = d3.arc()
  .innerRadius(outerRadius)
  .outerRadius(outerRadius)
  .startAngle(0)
  .endAngle(5);

var path = svgContainer.append("path")
  .style("fill", "none")
  .style("stroke", "#0B9B29")
  .style("stroke-width", stroke)
  .attr('stroke-linejoin', 'round')
  .attr("d", outerArc());

var point = path.node().getPointAtLength(path.node().getTotalLength() / 2);

var circle = svgContainer.append("circle")
  .attr("fill", "#0B9B29")
  .attr("cx", point.x)
  .attr("cy", point.y)
  .attr("r", 10);

var text = svgContainer.append("text")
  .attr("fill", "white")
  .attr("x", point.x)
  .attr("y", point.y)
  .attr("text-anchor", "middle")
  .attr("dominant-baseline", "central")
  .attr("font-size", "8px")
  .text(d3.format(".0%")(5 / (Math.PI * 2)));
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
&#13;
&#13;
&#13;

相关问题