svg的x和dx属性有什么区别?

Nat*_*ese 101 svg d3.js

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")
Run Code Online (Sandbox Code Playgroud)

当以下似乎做同样的事情时,设置y和dy的优点或原因是什么?

chart.append("text")
   .attr("x", 0)
   .attr("y", -3)
   .text("I am a label")
Run Code Online (Sandbox Code Playgroud)

Sco*_*ron 89

x并且y是绝对坐标,dx并且dy是相对坐标(相对于指定的xy).

根据我的经验,这是不常见的使用dxdy<text>元素(虽然它可能是编码方便,如果你,例如,有定位文本的一些代码,并调整它,然后分开的代码很有用).

dxdy当使用<tspan>嵌套在元素内的<text>元素来建立更多的多行文本布局时,它们非常有用.

有关更多详细信息,请查看SVG规范文本部分.

  • 在我看来,在“d3.js”中,它用于组合不同的单元。就像 `x="3" dx="0.5em"` 相当于 3 个像素 + 半个文本行。 (3认同)

ang*_*s l 68

要添加到Scott的答案中,与em(字体大小单位)一起使用的dy对于相对于绝对y坐标垂直对齐文本非常有用.这在MDN dy文本元素示例中介绍.

无论字体大小如何,使用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>
Run Code Online (Sandbox Code Playgroud)

在Codepen中查看它

如果不包含"dy = 0.35em",则单词会在文本底部周围旋转,并在旋转前的180对齐位置.包括"dy = 0.35em"将它们围绕文本的中心旋转.

请注意,无法使用CSS设置dy.

  • 万一其他人遇到这个问题,除非我设置 svg = d3.select("body").append("svg"); 然后在下一行做了 attr 。svg.attr({宽:500,高:300});。感谢分享! (2认同)