Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...