Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

496 CHAPTER 12 Drawing with HTML5


Even though SVG renders much better than the canvas, it takes time to scale and re-exe-
cute the commands, so performance is not as good. The canvas is preferable when perfor-
mance is more important.
SVG is XML-based, and you can embed SVG in your HTML page by using the <svg> ele-
ment. The content of the <svg> element contains the XML-based commands that make the
drawing. The <svg> element, plus its content, is part of the document object model (DOM),
so all of the <svg> element and its children are accessible from JavaScript. Events can also be
attached to any of the elements. However, you don’t want to write all the XML that’s required
to create a complex drawing. It’s typically best to use an SVG editor to create the drawing and
then embed the drawing into your webpage.
In this lesson, you learn how to use the <svg> element to embed a drawing in an HTML
page to display simple graphics. In addition, you learn how to use the <img> element to
display .svg files.

After this lesson, you will be able to:
■■Describe the <svg> element.
■■Implement the <svg> element.
■■Display SVG files using the <img> element.

Estimated lesson time: 20 minutes

Using the element


The <svg> element is a container for the XML-based commands. Using it in your HTML page
enables you to embed your drawing directly into the page. The following is an example of a
basic <svg> element.
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
</svg>

In this example, the width and height are set, and the XML namespace is defined to indi-
cate that this is an SVG drawing.

Creating a path
A path is a sequence of commands that create a complex shape. Use the <path> element,
which has id, fill, and d attributes, to create a path. The fill attribute is passed the color with
which you want to fill the path. The d attribute is for the <path> element’s data, which is
populated with the commands and typically starts with a command to move to the point at
which the drawing of the shape begins. The command to move is m or M. When the low-
ercase command is used, it indicates that the coordinates are relative. When the uppercase
command is used, it indicates that the coordinates are absolute.
Free download pdf