我正在使用 d3.js 制作旭日图创建工具,并且我正在尝试复制 this page 上的标签方式。翻转,使它们永远不会颠倒。问题是我将使用 rotate
和 transform
属性,但这已经用于定位标签。这是我当前的代码:
svg.selectAll("text")
.data(partition.nodes)
.enter()
.append("text")
.attr("transform", function(d) { return "rotate(" + ((d.x + d.dx / 2 - Math.PI / 2) / Math.PI * 180) + ")"; })
.attr("x", function(d) { return Math.sqrt(d.y); })
.attr("dx", "6") // margin
.attr("dy", ".35em") // vertical-align
.text(function(d) { return d.name;});
我找到了 tspan
rotate
属性,但事实证明这是一个转移注意力的事情,因为它会旋转各个字母。我的图表基于 this page .
提前致谢!
最佳答案
一种选择是将文本嵌套在组内。该组的定位方式与您当前定位文本的方式大致相同,只不过不使用“x”属性,而是使用带有 translate
的 transform
属性除了现有的 rotate
指令之外。请注意,转换的顺序在这里很重要;您需要先旋转然后平移。
然后,您可以对组内的文本应用局部转换。 IE。如果需要翻转,它会旋转 180 度。这样,文本就不需要移动到位——小组会处理这个问题——但在翻转时可能需要进行小的局部调整(而且,在这种情况下,ir 可能必须正确对齐) )。
下面的代码或多或少应该可以做到这一点,尽管我不可能在没有可用的 jsFiddle 的情况下测试和调整它。
svg.selectAll("g.label")
.data(partition.nodes)
.enter()
.append("g")
.attr("class", "label")
.attr("transform", function(d) {
// First, rotate the group (not the text) and then translate it
// by the same amount that used to be applied via "x" attr
return
"rotate(" + ((d.x + d.dx / 2 - Math.PI / 2) / Math.PI * 180) + ") " +
"translate(" + Math.sqrt(d.y) + ")";
})
.each(function(d, i) {
d3.select(this) // select the containing group (which was just created above)
.append('text') // append text inside the group
.attr("dx", "6") // margin
.attr("dy", ".35em") // vertical-align
.attr("transform", function(d) {
// Locally transform the text within the containing group:
// Label should be flipped if group's rotation is greater than Math.PI (aka 180 degs)
var shouldBeFlipped = d.x + d.dx / 2 - Math.PI / 2 > Math.PI;
return "rotate(" + (shouldBeFlippled ? 180 : 0) + ")"
})
.text(function(d) { return d.name;});
});
关于javascript - 如何旋转文本标签,使其不会上下颠倒 (SVG)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16091044/