HTML and CSS Reference
In-Depth Information
transform="translate(75,75)"
onclick="alert('Penguin Click');"Click
ontouchstart="alert('Penguin Touch');" />
<text x="75" y="125" text-anchor="middle"
font-family="Verdana" font-size="10" fill="black" >
A tilted birdhouse
</text>
</svg>
</body>
</html>
As mentioned, SVG provides a number of different primitives for drawing. Unlike Canvas, after you create
an element, it sticks around in the scene graph the same way that DOM elements do. You can move the element
around by modifying its
x
and
y
properties or by adding a
transform
property. SVG elements can also have
event handlers attached. If you click the image of the penguin on the desktop, you can trigger the
onclick
handler. If you touch it on a WebKit device, you'll trigger a “Penguin Touch” alert.
Each primitive element also has a set of properties specific to the element in question. Although a full over-
view of all the details of the SVG spec is out of scope for a single chapter, the following sections discuss some
of the details of a few of the primitive elements used previously. If you want to learn more about SVG, check
out the specification at
www.w3.org/TR/SVG/
.
NOTE
Android devices, as of this writing, don't support the
ontouchstart
event handler being added as
an attribute, but they do work when added manually via
addEventListener
.
<svg>
The base
<svg>
container element has already been briefly described, but a couple of additional attributes will
be important later in the chapter. (Attributes in SVG are case-sensitive, so make sure you match the case shown
in the text.) The
width
and
height
attributes are self-explanatory because they define the width and height
of the element inside of the HTML document. The
viewBox
attribute (the “B” in box is capitalized) is inter-
esting. It defines the portion of the SVG document that is visible inside of the SVG container.
viewBox
takes
four integer parameters (separated by spaces, not commas):
<svg width='WIDTH' height='HEIGHT' viewBox="X Y WIDTH HEIGHT"> ...
</svg>
As you may have figured out, from a game perspective you can use the
viewBox
as a camera into your
game. If you set a
WIDTH
and
HEIGHT
in the
viewBox
that is smaller than the
WIDTH
and
HEIGHT
on the
<svg>
element, objects in the SVG container appear zoomed in. If you set the
WIDTH
and
HEIGHT
to be lar-
ger than the container, elements zoom out. Setting the
X
and
Y
parameters essentially pans the camera around
the page.
If the aspect ratio of the
<svg>
element and the
viewBox
don't line up, how the content displays inside of
the container depends on the value of the
preserveAspectRatio
attribute. The default options ensure that
the content is scaled down, so the entire
viewBox
is visible inside of the container, with content centered in the
x
and
y
direction.
preserveAspectRatio
has a lot of configurable values, so if you need control over how