gpt4 book ai didi

javascript - 在 d3 路径内添加数字/文本

转载 作者:行者123 更新时间:2023-11-28 11:22:42 26 4
gpt4 key购买 nike

如何使用 d3 在弧内添加文本或数​​字标签?

我已经按照我想要的方式绘制了路径,但很难将文本放入其中?

我想在路径开头为每个路径添加“count”值

我已经在下面添加了到目前为止所拥有的内容以及创建了一支笔(请参阅下面的链接)

CODEPEN LINK

var width = 300, height = 300;
var twoPi = 2 * Math.PI; // Full circle
var formatPercent = d3.format(".0%");

var data = [
{ "count" : 1000 },
{ "count" : 800 },
{ "count" : 800 },
{ "count" : 700 }
];

var max = d3.max(data, function(d) {
return +d.count;
});

var percent = d3.max(data, function(d) {
return +d.count / 10;
});

var radius = .25;
var gap = 22;
var maxCount = max + percent;

var cx = width / 2.5;
var cy = height / 2.5;

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 10 + "," + height / 10 + ")");

svg.selectAll("path")
.data(data).enter()
.append("path")
.each(drawArc);

function drawArc(d, i) {
var ratio = d.count / maxCount;
var arc = d3.svg.arc()
.startAngle(0)
.endAngle(twoPi * ratio)
.innerRadius(0 + gap * radius)
.outerRadius(20 + gap * radius);

d3.select(this)
.attr("transform", "translate(" + cx + "," + cy + ")")
.attr("d", arc);
radius++;
}

最佳答案

这已经是 answered .

您需要为路径分配一个 ID,然后在文本节点中设置指向相应路径 ID 的 xlink:href 属性。

var text = svg.append("text")
.attr("x", 6)
.attr("dy", 15);

text.append("textPath")
.attr("xlink:href","#yourPathId")
.text("My counter text");

This is the codepen进行一些更改来反射(reflect)这一点。

关于javascript - 在 d3 路径内添加数字/文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29852536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com