15

是否有 rect 等效于 text 的 text-anchor 表示属性?

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

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

4

3 回答 3

6

我正在寻找同样的问题,发现这个帖子没有答案。这个问题很老了,但我把解决方案放在这里,有人可能会像我一样寻找它。

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

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

该解决方案目前仅适用于 Chrome

因此,要实现“嘿,将我的矩形的中心放在 (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%);
}

jsfiddle上的代码片段

.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;
}
<!-- One can use translate with percents to achieve anchor like mechanics -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
  <rect fill="lightblue" x="0" y="0" width="100%" height="100%"></rect>

  <!-- Use translate to achieve anchor mechanics -->
  <rect class="rect-anchor-0-0" x="150" y="150" width="200" height="35" />
  <rect class="rect-anchor-50-50" x="150" y="150" width="200" height="35" />

  <!-- Rect x,y position mark for convenience -->
  <circle cx="150" cy="150" r="2" fill="red"></circle>
</svg>

于 2015-11-13T10:27:12.087 回答
2

rect其他 SVG 元素(包括)没有这样的东西,请参阅规范。您必须自己计算位置。

于 2013-11-01T14:17:41.193 回答
1

如果您想在附加后立即执行此操作:

    .append('rect')
      .attr('width', 10)
      .attr('height', 5)
      // Center rectangle
      .attr('transform', function() {
        return `translate(-${this.getAttribute('width') / 2}` +
          `, -${this.getAttribute('height') / 2})`;
      });
于 2020-01-28T16:05:46.147 回答