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
412 views
in Technique[技术] by (71.8m points)

html - How do I scale an SVG polygon in ems?

I'm embedding an <svg> element directly in an HTML5 document, and I want to scale a repeating background pattern in terms of the page's font size. No problem, SVG supports CSS units, so I can just specify the size in ems, right?

The SVG spec claims "All coordinates and lengths in SVG can be specified with or without a unit identifier." And, indeed, both of these do exactly what I was hoping for:

<rect x='1em' y='2em' width='3em' height='4em' />
<circle cx='6em' cy='7em' r='8em' />

But polygons (for example) have their own completely different definition of the word "coordinate," such that this raises an error instead of drawing a 1 em triangle:

<polygon points='0 0, 0 1em, 1em 0' />

Paths are the same way -- understandably, since they're already using the letters for a different purpose.

And transformations such as "scale" expect a "number," not a "coordinate" or "length", so this isn't allowed either (my browser seems to silently ignore the "transform" attribute):

<polygon points='0 0, 0 1, 1 0' transform='scale(1em)' />

So I guess I can't even figure out how to draw a 1 em triangle, much less anything more complicated. Am I overlooking a reasonable way of doing it? What about an unreasonable way? Should I give up and use a <canvas> element instead, or would that be even worse?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can wrap your polygons in an inner <svg> element to scale them as you wish. The viewBox controls the coordinate system of the objects it contains and the height and width attributes control how big it looks.

<svg xmlns="http://www.w3.org/2000/svg">
  <svg viewBox="0 0 1 1" height="1em" width="1em" y="7em">
      <polygon points='0 0, 0 1, 1 0' />
  </svg>
  <circle cx='6em' cy='7em' r='2em' />
</svg>

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

...