In this chapter, a high-level overview of Scalable Vector Graphics (SVG) will be presented by explaining how it operates and what elements it encompasses. In a browser context, SVG is very similar to HTML and is one of the means by which D3 expresses its power. Understanding the nodes and attributes of SVG will empower us to create many kinds of visualizations, not just maps. This chapter includes the following points:
- A general overview of SVG and its key elements
- The SVG coordinate system
- The primary elements of SVG (lines, rectangles, circles, polygons, and paths)
SVG, an XML markup language, is designed to describe two-dimensional vector graphics. The SVG markup language resides in the DOM as a node that describes exactly how to draw a shape (a curve, line, circle, or polygon). Just like HTML, SVG tags can also be styled from standard CSS. Note that, because all commands reside in the DOM, the more shapes you have, the more nodes you have and the more work for the browser. This is important to remember because, as SVG visualizations become more complex, the less fluidly they will perform.
The main SVG node is declared as follows:
<svg width="200" height="200"></svg>
This node's basic properties are width and height; they provide the primary container for the other nodes that make up a visualization. For example, if you wanted to create 10 sequential circles in a 200 x 200 box, the tags would look like this:
<?xml version="1.0"?> <svg width="200" height="200"> <circle cx="60" cy="60" r="50"/> <circle cx ="5" cy="5" r="10"/> <circle cx="25" cy="35" r="45"/> <circle cx="180" cy="180" r="10"/> <circle cx="80" cy="130" r="40"/> <circle cx="50" cy="50" r="5"/> <circle cx="2" cy="2" r="7"/> <circle cx="77" cy="77" r="17"/> <circle cx="100" cy="100" r="40"/> <circle cx="146" cy="109" r="22"/> </svg>
Note that 10 circles would need 10 nodes in the DOM, plus its container.
SVG contains several primitives that allow the developer to draw shapes quickly.
We will cover the following primitives throughout this chapter:
- circle: A standard circle with a defined radius and position attributes
- rect: A standard rectangle with height, width, and position attributes
- polygon: Any polygon, described by a list of points
- line: A line with start and end points
- path: A complex line created through a series of drawing commands