svg的x和dx属性(或者y和dy)有什么区别?什么时候是使用轴移位属性(dx)与位置属性(x)的合适时机?
例如,我注意到很多d3示例都是这样做的
chart.append("text")
.attr("x", 0)
.attr("y", 0)
.attr("dy", -3)
.text("I am a label")
当下面的内容似乎做了相同的事情时,同时设置y和dy有什么好处或理由呢?
chart.append("text")
.attr("x", 0)
.attr("y", -3)
.text("I am a label")
发布于 2013-10-01 22:52:06
x
和y
是绝对坐标,dx
和dy
是相对坐标(相对于指定的x
和y
)。
根据我的经验,在<text>
元素上使用dx
和dy
并不常见(尽管它可能有助于方便编码,例如,如果您有一些代码用于定位文本,然后使用单独的代码对其进行调整)。
当使用嵌套在<text>
元素中的<tspan>
元素来建立更美观的多行文本布局时,dx
和dy
最有用。
有关更多详细信息,请查看Text section of the SVG spec。
发布于 2013-10-02 15:15:09
为了补充Scott的答案,与em (字体大小单位)一起使用的dy对于相对于绝对y坐标垂直对齐文本非常有用。MDN dy text element example中介绍了这一点。
使用dy=0.35em可以帮助将文本垂直居中,而不考虑字体大小。如果您想要围绕绝对坐标所描述的点旋转文本的中心,它也很有用。
<style>
text { fill: black; text-anchor: middle; }
line { stroke-width: 1; stroke: lightgray; }
</style>
<script>
dataset = d3.range(50,500,50);
svg = d3.select("body").append("svg");
svg.attr('width',500).attr('height', 500);
svg.append("line").attr('x1', 0).attr('x2', 500).attr('y1', 100).attr('y2', 100);
svg.append("line").attr('x1', 0).attr('x2', 500).attr('y1', 200).attr('y2', 200);
group = svg.selectAll("g")
.data(dataset)
.enter()
.append("g");
// Without the dy=0.35em offset
group.append("text")
.text("My text")
.attr("x",function (d) {return d;})
.attr("y",100)
.attr("transform", function(d, i) {return "rotate("+45*i+","+d+",100)";});
// With the dy=0.35em offset
group.append("text")
.text("My text")
.attr("x",function (d) {return d;})
.attr("y",200)
.attr("dy","0.35em")
.attr("transform", function(d, i) {return "rotate("+45*i+","+d+",200)";});
<script>
如果不包括"dy=0.35em",单词将围绕文本底部旋转,180后在旋转前的位置下方对齐。包含"dy=0.35em“将使它们围绕文本的中心旋转。
请注意,不能使用CSS设置dy。
https://stackoverflow.com/questions/19127035
复制相似问题