svg - 缩放父元素时保留后代元素的大小

标签 svg

我有一个 XHTML 页面,其中嵌入了 SVG 作为 <svg>元素。我需要实现缩放,但有一个要求,内部 <text>元素不能缩放。一个明显的解决方案是

<svg ...>
  <!-- Root <g> to programmatically `setAttribute("transform", ...)` -->
  <g transform="scale(0.5)">
    <!-- Various inner elements here -->
    <!-- Here is a text element.
         Additional <g> is to apply text position which
         *must* depend on the scaling factor set above -->
    <g transform="translate(100 50)">
      <!-- Apply the opposite scaling factor.
           Must be done for every `<text>` element on each change of the scaling factor... -->
      <text x="0" y="0" transform="scale(2)">Hello, World!</text>
    </g>
  </g>
</svg>

还有比这更好的解决方案吗?也许,有一种方法可以“重置”内部 <text> 上的结果缩放因子。元素?代码必须在 Firefox 和 Chrome 中工作。

UPD .还有一个选项可以将文本元素放置在被缩放的元素之外并手动控制文本元素的位置。它避免了由于缩放而出现在文本上的视觉故障。目前我使用这种方法。

最佳答案

transform="ref(svg)"SVG Tiny 1.2 中定义.据我所知,除 Opera (Presto) 之外的任何浏览器都没有实现这一点。

<svg xmlns="http://www.w3.org/2000/svg" font-size="24" text-rendering="geometricPrecision">
  <!-- Root <g> to programmatically `setAttribute("transform", ...)` -->
  <text x="0" y="1em" stroke="gray" fill="none">Hello, World!</text>
  <g transform="scale(0.5) rotate(25)">
    <!-- Various inner elements here -->
    <!-- Here is a text element.
         Additional <g> is to apply text position which
         *must* depend on the scaling factor set above -->
    <g transform="translate(100 50)">
      <!-- Apply the opposite scaling factor.
           Must be done for every `<text>` element on each change of the scaling factor... -->
      <text x="0" y="1em" transform="ref(svg)">Hello, World!</text>
    </g>
  </g>
</svg>

在上面的例子中,文本应该出现在灰色轮廓的位置(在左上角)。不应将旋转或缩放应用于具有 transform="ref(svg)" 的元素,为了转换的目的,它就好像它是根 svg 元素的直接子元素。

关于svg - 缩放父元素时保留后代元素的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8880668/

相关文章:

输出到 OpenGL(交互式)和 SVG(用于打印)的 Java 库

javascript - 基于动画 SVG 定位 SVG

javascript - 如何在 amchart js 库中设置自定义颜色?

javascript - 为什么不绘制以编程方式插入的 SVG <tspan> 元素,d3.js 除外?

javascript - 使用 svg map 激活类

javascript - 悬停效果仅适用于字母(而非容器)

javascript - 使用 jQuery/JS 时如何使用 &lt;input type=number> 更改 `rect` 框的大小和坐标

html - 跨域 svg Sprite

javascript - 当设置一个 svg 显示 : none, 时,其他 SVG 元素变为黑色

html - 仅在与主要形状接触时才产生粘性效果