500 CHAPTER 12 Drawing with HTML5
Making the SVG scalable
The SVG file currently has the contents from the <svg> element, but you need to make some
changes to make the image scale. First, change the height and width setting to 100 percent
and then add a viewBox attribute to the <svg> element.
The viewBox attribute describes the part of the canvas you want the viewer to see. Even
though the drawing covers the entire computer screen, the figure on your drawing might only
exist in a small part of the drawing. The viewBox attribute enables you to tell the parser to
zoom in on that part to eliminate the extra white space. Set viewBox to get the proper zoom
capabilities when you resize your HTML page.
The viewBox attribute has four parameters: the minimum x coordinate, the minimum y
coordinate, the width, and the height. This enables you to describe the rectangular area to
be displayed. In this example, some white space at the top and bottom of the drawing will be
cropped, so the following is the viewBox attribute setting.
viewBox="0 50 500 175"
This setting crops 50 pixels from the top and limits the viewing height to 175 pixels. The
original width of the drawing was 500 pixels, and there isn’t a lot of white space on the sides,
so it is left as is. The following is the content of the .svg file after the changes are made.
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"
viewBox="0 50 500 175" >
<path d="m267 76 l-21 -4 -144 0 -90 47 0 54 11 11 23 0 15 -30 15 -10 30 0
15 10 15 30 220 0 15 -30 15 -10 30 0 15 10 15 30 l25 0 7 -7
-13 -38 -20 -10 -95 -15 z" fill="blue" id="carBody" />
<path d="m65 105 l40 -25 65 0 0 34 -112 0 z" fill="white" id="rearWindow" />
<path d="m300 105 l-40 -25 -78 0 0 34 122 0 z" fill="white" id="frontWindow" />
<circle r="35" cy="185" cx="90" fill="black" id="rearWheel" />
<circle r="35" cy="185" cx="400" fill="black" id="frontWheel" />
</svg>
In the svg.css file, the following style rule has been added to resize the <img> element
automatically when the HTML page is resized.
img {
width: 100%;
}
Display the HTML page. You might need to refresh the page to see the change. The <img>
element is now the size of the HTML page, and resizing the page resizes the <img> element,
as shown in Figure 12-25.