DEV Community

Cover image for Scalable Vector Graphics: Drawing Basics
Play With Codes
Play With Codes

Posted on • Edited on

Scalable Vector Graphics: Drawing Basics

If you’re completely new to SVGs, it may help to read the following articles first:

  • Scalable Vector Graphics: an Overview
  • 7 Reasons to Consider SVGs Instead of Canvas

SVG Co-ordinate Grid

An SVG is defined in whatever coordinate space you give it. That space does not necessarily correlate with pixels, centimeters, inches, or other absolute units, because an SVG can be scaled to any dimension.

The SVG’s viewBox attribute determines the co-ordinates the image uses. The following SVGs would look identical when scaled to the same size:

a viewBox of 0,0 to 200,100 with a line from 0,0 to 100,50
a viewBox of 0,0 to 300,150 with a line from 0,0 to 150,75
a viewBox of 0,0 to 30,15 with a line from 0,0 to 15,7.5 (fractions of a unit are permitted)

SVG XML Document

An SVG image is an XML document that follows strict conventions (closing tags, quoted attributes, etc). When SVGs were first developed in 1999, files required an XML declaration and DOCTYPE at the top of the document above the root <svg> element:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "https://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="https://www.w3.org/2000/svg">

  <!-- image data -->

</svg>
Enter fullscreen mode Exit fullscreen mode

You may still encounter this format, but it’s more usual for .svg files to use a single root element:

<svg xmlns="https://www.w3.org/2000/svg">

  <!-- image data -->

</svg>
Enter fullscreen mode Exit fullscreen mode

Also visit: Best Web Hosting Review Site

Grouping Elements

Any set of elements (lines, circles, rectangles, text, etc.) can be grouped using <g>...</g> tags. In essence, it’s similar to grouping drawing objects in a graphics package so they can be manipulated as a single item.

For example, you could define a root group node so the whole image can be manipulated via JavaScript or CSS:

<g id="main">
  <!-- drawing elements to go here -->
</g>
Enter fullscreen mode Exit fullscreen mode

A single group can have any number of inner groups with nesting as necessary.

Lines

A single line between two points is drawn using the line element:

<line x1="10" y1="10" x2="100" y2="200"
stroke="#999" stroke-width="5" stroke-linecap="round" />
Enter fullscreen mode Exit fullscreen mode

Polylines

Polylines define a set of connected straight line segments:

<polyline points="580,10 560,390 540,200 520,390 400,390"
stroke="#c00" stroke-width="5" stroke-linecap="round"
stroke-linejoin="round" fill="none" />
Enter fullscreen mode Exit fullscreen mode

Read more on SitePoint

Thanks

Top comments (0)