Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

svg - Preserve descendant elements' size while scaling the parent element

I have an XHTML page with SVG embedded into it as an <svg> element. I need to implement scaling, but there is a requirement that inner <text> elements must not scale. An obvious solution is

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

Is there a better solution than that? Maybe, there is a way to "reset" the resulting scaling factor on inner <text> elements? The code must work in Firefox and Chrome.

UPD. There is also an option to place text elements outside the element being scaled and manually control text elements' positions. It avoids visual glitches appearing on the text because of scaling. Currently I use this method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is transform="ref(svg)" which is defined in SVG Tiny 1.2. To the best of my knowledge this is not implemented in any browsers except 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>

In the above example the text should appear where the gray outline is (in the top-left corner). No rotation or scaling should be applied to the element that has transform="ref(svg)", for the purposes of transformations it's as if it was a direct child of the root svg element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...