我有一个 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/