HTML5 and CSS3, Second Edition

(singke) #1

Tip 19


Tip 19. Creating Vector Graphics with SVG


We’re not limited to drawing graphics on the canvas. HTML5 documents
support Scalable Vector Graphics, or SVG. Instead of using JavaScript to plot
lines and draw shapes, we define lines, curves, circles, rectangles, and poly-
gons using XML. Graphics in SVG are true vector graphics, meaning that
instead of being made up of pixels like raster graphics, they use math to
define the lines. That means we can easily resize vector graphics without
blurriness or loss of quality, unlike the raster graphics of the Canvas.

To learn about SVG, we’ll use SVG’s XML syntax to redraw the AwesomeCo
logo we drew before.

First we create a simple HTML skeleton with an element on the page:


html5_svg/index.html
<!DOCTYPEhtml>
<htmllang='en'>
<head>
<metacharset="utf-8">
<title>AwesomeCoLogoTest</title>
</head>
<body>
<scripttype="image/svg+xml">
<svgid="awesomeco_logo"width="900"height="80">
</svg>
</script>
</body>
</html>

We define the <svg> tag within a <script> tag with the content type of
image/svg+xml. This will ensure that the SVG content is skipped when browsers
parse the HTML elements of the page. Within the <svg> tag we also specify
the height and width of the SVG element. The XML that defines the image
we’re going to create goes between the opening and closing <svg> tags.

Drawing Lines


Let’s start by drawing the main line of the logo that the text rests on. When
we did this using the canvas, we used a path, but SVG supports something
called a <polyline>, which is designed to create lines with angles. We can whip
up the main line, including the angled part, with this code:

Chapter 6. Drawing in the Browser • 126


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf