SVG Basics

Last updated on 2020-04-13 15:42:12 -0300

<svg>
  <g transform="translate(-100,-50),scale(1.5)">
    <text x="0" y="100" font-size="50" fill="black">Some Text</text>
    <line x1="5" y1="5" x2="90" y2="90" stroke-width="2.5" stroke="red"/>
    <rect x="60" y="95" height="30" width="50"/>
    <circle cx="80" cy="50" r="40"/>
    <ellipse cx="80" cy="110" rx="75" ry="105" fill="#538"/>
    <path d="M 100 100 L 200 200" stroke="black"/>
  </g>
</svg>

Most tags can also have the attribute opacity (default = 1).

1. <line>

x1, y1, x2, y2: coordinates
stroke: color
stroke-width: width (default = 1)
stroke-linecap: "flat" (default) or "round"
stroke-dasharray: e.g. "5,2,2,2"

See also the <marker> tag for arrows and such.

2. <rect>

x, y, height, width: coordinates
fill: fill color
stroke*: border attributes

See also the <gradient> tag for more complex rect fills.

3. <circle>

cx, cy, r: coordinates
Other attributes as in <rect>

4. <ellipse>

cx, cy, rx, ry: coordinates
Other attributes as in <rect>

5. <path>

In addition to fill and stroke* attributes, <path> has a string attribute d of arbitrary length that specifies a complex path.

The path string (attr d) is a series of drawing commands as in turtle.

RaphaelJS docs have good explanation of path:
http://dmitrybaranovskiy.github.io/raphael/reference.html#Paper.path

M x,y: move to (x,y)
L x,y: line to (x,y)
Q x1,y1 x2,y2: quadratic Bézier curve to (x2,y2) with control (x1,y1)
C x1,y1 x2,y2 x3,y3: cubic Bézier curve to (x3,y3) with controls (x1,y1) and (x2,y2)
A rx ry XAR large-arc-flag sweep-flag x y: some kind of arc
Z: close the path

Some command letters can be omitted:
"M 0,0 50,50" == "M 0,0 L 50,50"
"M 0,0 50,50 0,50 z" == "M 0,0 L 50,50 L 0,50 z"

6. <g>

This tag is simply used to group elements.
Grouped elements can inherit attributes from the <g> element:

<g fill="blue">
  <circle cx="80" cy="50" r="40" fill="inherit"/>
</g>

7. <use>

This tag allows code reuse:

<g fill="blue">
  <g id="MyGroup">
    <circle cx="80" cy="50" r="40" fill="inherit"/>
  </g>
</g>
<use xlink:href="MyGroup" transform="translate(120,0)" fill="green"/>