SVG: ViewBox, User Coordinate's Unit Size

By Xah Lee. Date: .

When in user coordinate, any unit specified (for line thickness, font, etc) is also in user coordinate.

For example, here's a line thickness of 5, with default coordinate, of width 100 and height 100 pixels.

<svg width="100" height="100">
<path d="M 0 0 L 100 100 "
style="stroke:black; fill:yellow; stroke-width:5" />

Here's a line thickness of 0.5, with user coordinate 10 per side, in a svg box of width 100 and height 100 pixels.

<svg width="100" height="100" viewBox="0 0 10 10" >
<path d="M 0 0 L 100 100 "
style="stroke:black; fill:yellow; stroke-width:0.5" />
</svg>

How to Get the Right Line Thickness or Font Size

Normally, without user coordinate, line thickness of 1 is a natural size, they are not too thick, not too thin, in any device.

(Similarly, font size of 16 is a proper size.)

But when using user coordinate, line thickness of 1 may cover the screen or too thin to be visible.

We want to find the “right size” that corresponds to 1 pixel in default (absolute) coordinate.

Here's a formula:

The s is the scaling factor to multiply by user coordinate unit to get a equivalent length in absolute coordinate.

For example,

See also: JS: Find Element Width

SVG tutorial

  1. SVG Basics
  2. Path
  3. Path Elliptical Arc
  4. Circle Arc
  5. Specifying Styles
  6. Shape Styles
  7. Viewport
  8. viewBox
  9. ViewBox Unit Size
  10. Coordinate Transformation
  11. Text Element
  12. Font Size
  13. Structure Elements
  14. Scripting SVG
  15. SVG Clock
  16. Animation

Canvas Intro

  1. Canvas vs SVG
  2. Canvas intro
  3. Demo: Halma
  4. Demo: Raycaster
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog