Mastering SVG
上QQ阅读APP看书,第一时间看更新

Creating a simple SVG image

If you're at all familiar with HTML, then the basics of an SVG document are going to be familiar to you. So let's get the mystery out of the way early and take a look at a simple SVG document. 

The following code sample shows the basic structure of SVG. The first element is the standard xml declaration, indicating that the following should be parsed as an XML document. The second element is where the fun begins. It defines the root SVG element (in the same way that there's a root HTML element in an HTML document). height and width define the intrinsic dimensions of the document. The XML NameSpace (xmlns) is a reference to the schema that defines the current XML element. You'll learn about viewBox in more detail in the next chapter. There are many other attributes possible on an SVG element. You will learn more about them throughout this book.

In this first example, following the SVG element, there's a single SVG text element. The text element, like the SVG element, has many possible attributes that you'll learn about as you make your way through the book. In this case, there are four attributes related to the display of the element. The x and y attributes represent the position of the top-left corner of the text element as points on a coordinate plane. font-family maps to the familiar CSS property of the same name and defines the specific font that should be used to display the text. font-size also maps to the common CSS property of the same name.

The attributes that accept length values (in this example width, height, and  font-size) are provided without a unit (for example, px, em, and  %.) When these values are presented as attributes, the unit is optional. If no unit is provided, the values are specified as being user units in the user space. You'll learn more about the way that values are calculated in SVG throughout the book. For now, just remember that, in practice, user units will be equivalent to pixels.   

Finally, there is the content of the text element, the simple message Hello SVG:

<?xml version="1.0" encoding="UTF-8"?>
<svg width="250" height="100" viewBox="0 0 250 100" version="1.1" xmlns=”http://www.w3.org/2000/svg”>
<text x="0" y="50" font-family="Verdana" font-size="50">
Hello SVG
</text>
</svg>

Saved as 1-1-hello-world.svg and opened in a browser, the previous markup renders as in the following screenshot:

Now that you've seen the most basic example of an SVG document, let's take a look at the basic usage of SVG images and elements in a variety of ways.