svg 的 x 和 dx 属性有啥区别?

Posted

技术标签:

【中文标题】svg 的 x 和 dx 属性有啥区别?【英文标题】:What is the difference between svg's x and dx attribute?svg 的 x 和 dx 属性有什么区别? 【发布时间】:2013-10-08 06:04:46 【问题描述】:

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")

【问题讨论】:

【参考方案1】:

xy是绝对坐标,dxdy是相对坐标(相对于指定的xy)。

根据我的经验,在 <text> 元素上使用 dxdy 并不常见(尽管如果您有一些用于定位文本的代码然后单独的代码,这可能有助于编码方便调整它)。

dxdy 在使用嵌套在 <text> 元素内的 <tspan> 元素来建立更精美的多行文本布局时非常有用。

更多详情您可以查看Text section of the SVG spec。

【讨论】:

在我看来d3.js中,它用于组合不同的单元。比如x="3" dx="0.5em",相当于 3 个像素 + 半个文本行。【参考方案2】:

为了补充 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>

View it in Codepen

如果您不包含“dy=0.35em”,则文字会围绕文本底部旋转,并且在 180 之后对齐到旋转前的下方。包含“dy=0.35em”会使它们围绕文本中心旋转。

注意 dy 不能使用 CSS 设置。

【讨论】:

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

以上是关于svg 的 x 和 dx 属性有啥区别?的主要内容,如果未能解决你的问题,请参考以下文章

dx和 opengl 有啥区别?

SVG 和 HTML5 Canvas 有啥区别?

如何操作SVG Text

matlab中mesh和surf有啥区别

SVG文本

DOM和BOM有啥区别吗?