Rect相当于text的text-anchor表示属性?

13 svg d3.js

是否有一个rect相当于text的text-anchor表示属性?

我希望能够从左/右侧放置一个矩形或根据情况.我知道可以通过一些简单的计算来完成,但我只是想知道是否存在内置的东西.

文本锚定表示属性的链接... https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor

gar*_*rek 6

我正在搜索相同的问题,但发现此帖子没有答案。这个问题已经很老了,但我在这里提出的解决方案可能会像我一样寻找。

当指定svg rect的(x,y)时,将被视为:“将rect的左上角放在点(x,y)上”。但是可能有人希望将(x,y)视为:“嘿,将我的矩形的中心放在(x,y)”“嘿,将我的矩形的右上角放在(x,y)”。为此,使用了锚定机制,但svg中没有这样的机制。

您仍然可以通过转换(使用css或属性)来实现锚机制。可能是因为transform.translate中的百分比值是相对于应用的形状(而不是其父对象)计算的。

该解决方案仅适用于铬

因此,要实现“嘿,将我的矩形的中心放置在(x,y)”,您需要将锚点设置为(0.5,0.5)。这是如何通过转换完成的:

.rect-anchor-50-50 {
  /* 
    Precents in translate are calculated relative to
    the applied rectangle, but not its parent.
    Set anchor to (0.5, 0.5) or (center, center).
    */
  transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)

jsfiddle上的代码片段

.rect-anchor-50-50 {
  /* 
    Precents in translate are calculated relative to
    the applied rectangle, but not its parent.
    Set anchor to (0.5, 0.5) or (center, center).
    */
  transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
.rect-anchor-0-0 {
  fill: #afafaf;
}
.rect-anchor-50-50 {
  /* 
    precents in translate are calculated relative to
    the applied rectangle, but not its parent
    */
  transform: translate(-50%, -50%);
  fill: #afcfae;
  opacity: 0.75;
}
.group {
  fill: red;
}
svg {
  fill: lightblue;
}
Run Code Online (Sandbox Code Playgroud)


Lar*_*off 1

rect其他 SVG 元素(包括)没有类似的情况,请参阅规范。您必须自己计算位置。