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")
x
和 y
是绝对坐标,dx
和 dy
是相对坐标(相对于指定的 x
和 y
)。
根据我的经验,在 <text>
元素上使用 dx
和 dy
并不常见(尽管如果您有一些用于定位文本的代码,然后使用单独的代码来调整它,这可能有助于编码方便)。
当使用嵌套在 <text>
元素内的 <tspan>
元素来建立更精美的多行文本布局时,dx
和 dy
最有用。
有关更多详细信息,您可以查看 Text section of the SVG spec。
为了补充斯科特的答案,与 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。
不定期副业成功案例分享
d3.js
中,它用于组合不同的单位。比如x="3" dx="0.5em"
,它等于 3 个像素 + 半个文本行。