Chapter 2. SVG Text Basics

For the simplest use cases, SVG text is straightforward. A short label can be added to a diagram with a single markup element and a pair of attributes.

SVG text, like SVG shapes, are positioned within a two-dimensional coordinate system. The coordinate system can be controlled by viewBox attributes and transform properties, but by default it starts in the top-left corner of the graphic. All points in the image are defined by their position relative to that origin point, along the horizontal x-axis and vertical y-axis.

The rest of the book will assume you are familiar with the SVG coordinate system. If any of that sounded confusing, you might have some background reading to do.

Letters on a Page

SVG text is, conveniently enough, drawn using the <text> element. Attributes on the <text> element define the position at which to start writing. The child text content of the element provides the words and letters to be written. It looks something like this:

<text x="10px" y="80%">SVG Text</text>

Put that code in a 400×80 SVG file, on top of a background rectangle, as in Example 2-1, and the result looks like Figure 2-1.

Example 2-1. Defining text within an SVG
<svg xmlns="http://www.w3.org/2000/svg"
     xml:lang="en"
     width="4in" height="0.8in" viewBox="0 0 400 80" >
    <title>Basic SVG Text</title>
    <rect width="100%" height="100%" fill="lightYellow" />
    <text x="10px" y="80%">SVG Text</text>
</svg>
Figure 2-1. Unstyled text in an SVG

Which…isn’t particularly ...

Get SVG Text Layout now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.