gpt4 book ai didi

javascript - 无法使用 path.centroid() 找到路径对象的中心

转载 作者:行者123 更新时间:2023-12-01 01:15:15 25 4
gpt4 key购买 nike

我想为 d3 map 中的每个社区添加一个社区名称。

我在这段代码中使用了 centroid() 函数。

var mapLabel = svg.selectAll("text")
.data(json)
.enter()
.append("text")
.text(function (d) {
return d.properties.nhood;
})
.attr('transform', function (d) {
return 'translate(' + path.centroid(d) + ')';
})
.attr('font-size', '6pt');

它将每个社区的名称放在远离中心的位置。

Images

Large version .

我尝试过 this代码也。

function addText(p)
{
var t = document.createElementNS("http://www.w3.org/2000/svg", "text");
var b = p.getBBox();
t.textContent = "a";
t.setAttribute("transform", "translate(" + (b.x + b.width/2) + " " + (b.y + b.height/2) + ")");
t.setAttribute("fill", "red");
t.setAttribute("font-size", "14");
p.parentNode.insertBefore(t, p.nextSibling);
}

var paths = document.querySelectorAll("path");
for (var p in paths)
{
addText(paths[p])
}

该代码可以将文本添加到每个 SVG 的中心,但我不知道如何让它为每个邻域添加自定义文本。相反,我得到了四十一次“a”。

我也尝试过 getBBox() 。我无法访问该函数,遇到了 getBBox() is not a function 错误。

这是创建 map 的代码部分。

var projection = d3.geoIdentity()
.reflectY(true)
.fitSize([w, h], jsonClone)

var pathFlipped = d3.geoPath()
.projection(projection);

const mapSelection = svg.selectAll("path")
.data(json)

mapSelection
.enter()
.append("path")
.attr("d", pathFlipped)
.style("fill", "lightgrey")

var mapLabel = svg.selectAll("text")
.data(json)
.enter()
.append("text")
.text(function (d) {
return d.properties.nhood;
})
.attr('transform', function (d) {
return 'translate(' + path.centroid(d) + ')';
})
.attr('font-size', '6pt');

这是 full map 的演示.

最佳答案

您需要对文本使用与路径相同的投影

.attr('transform', function(d) { return 'translate(' + pathFlipped.centroid(d) + ')'; })

关于javascript - 无法使用 path.centroid() 找到路径对象的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54822369/

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