Web Animation using JavaScript: Develop & Design (Develop and Design)

(Joyce) #1

here for demonstration purposes, but (as with HTML) it’s considered best practice to
specify SVG styling properties within a CSS stylesheet. Also as with HTML, stylesheet
classes target SVG elements via their id, class, or tag types.


Where the SVG and HTML specifications fundamentally differ is in their range of
accepted HTML attributes and CSS properties. SVG elements accept only a few of the
standard CSS properties. Further, SVGs accept a special set of attributes, called
presentational attributes, which include fill, x, and y. (fill specifies which color to
fill a shape with, whereas x and y define the position of the element’s top-left corner.)
These attributes define how an element is visually rendered on its canvas. Let’s run
through a few of them, using rect as a sample SVG element:


Click here to view code image



Here, the width and height attributes work as you’d expect. The unique x and y
attributes define the rectangle’s coordinates within the canvas. These values simply
position the rectangle relative to an x = 0, y = 0 origin point. Unlike HTML, SVG
positioning is not defined with top, right, bottom, left, float, or margin CSS
properties; SVG positioning logic is fully dictated by explicitly defined coordinates. In
other words, an SVG element’s positioning doesn’t affect the position of its sibling
elements; instead of pushing each other around the page, SVG siblings simply overlap one
another.

Now let’s take a look at the circle element. Its rendering is specified via coordinates
that designate its center point (cx and cy) along with a radius value (r) that designates its
length:


Click here to view code image



Pretty simple, right? SVG elements use the same markup structure as HTML elements,
so all the code samples in this chapter should feel familiar.

Note that there are many other types of SVG elements, including ellipse, line, and text.
See the end of this chapter for further details.


SVG styling


SVG elements accept a variety of special styling properties that are not available to HTML
elements. SVG’s fill property, for example, is similar to background-color in
CSS, stroke is similar to border-color, and stroke-width is similar to
border-width. Take a look at this example:


Click here to view code image
<svg version=“1.1” width=“500” height=“500”
xmlns=“http://www.w3.org/2000/svg”>
<circle cx=“100” cy=“100” r=“30” style=“fill: blue” />
<rect id=“rect” x=“100” y=“100” width=“200” height=“200” style=“fill:
green; stroke: red; stroke-width: 5px” />



Above, the circle element is filled with solid blue, and the rect element is filled
Free download pdf