如何在Arc的末尾添加文本

Dal*_*y S 2 html javascript 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());
Run Code Online (Sandbox Code Playgroud)
<head>
  <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
Run Code Online (Sandbox Code Playgroud)

例如

在此处输入图片说明

Ger*_*ado 5

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

var point = path.node().getPointAtLength(path.node().getTotalLength() / 2);
Run Code Online (Sandbox Code Playgroud)

注意除以2:这是必要的,因为圆弧先到达终止角度,然后再返回起始位置。

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

这是您所做的更改的代码:

var point = path.node().getPointAtLength(path.node().getTotalLength() / 2);
Run Code Online (Sandbox Code Playgroud)
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)));
Run Code Online (Sandbox Code Playgroud)

  • 哇,你让我开心! (2认同)
  • 谢谢杰拉多!您也让我开心了:)简单优雅的解决方案! (2认同)