Creating and Editing SVG Graphics

  • 7/15/2012
Learn the core concepts to begin tapping into your visual creativity. The authors walk you through a process that uses all of the basic shape elements of SVG.
  • Order becomes beauty

    beyond infinite planes

    and the undeciphered dense text

    a mosaic flower, fiery,

    chaos tamed in fullness,

    spring.

  • Orides Fontela

By the end of this chapter, you will have explored the core concepts and practiced the basic skills to begin tapping into your visual creativity. One great thing about programming graphics is that you can usually visualize your work almost immediately. To demonstrate this, you’ll walk through a process that uses all of the basic shape elements of SVG. As a teaser, here’s a look at one of the graphics that you will build in this chapter.

This graphic incorporates all of the basic shapes, the simple Bézier curve, more complex cubic Bézier curves, and bitmap images. It also demonstrates the logical grouping and reusing of related graphics, and finally, how to pull everything together into a reusable tiling pattern, which is also known as tessellation of the plane.

Creating Basic Vector Shapes

To get started, we’ll go over the six basic shape elements: <line>, <rect>, <circle>, <ellipse>, <polyline>, and <polygon>.

Lines

To create a visible line in SVG, simply set the x2 and y2 values of the <line> element. You can set the line’s color and other properties as well using the stroke-related attributes.

httpatomoreillycomsourcemspimages1261171.png
<line x2="300" y2="100" stroke="green" stroke-width="10" stroke-linecap="round" />

Brief Review of SVG Presentation Attributes

Besides the command attributes that define a shape’s position, radius, width, and height, SVG also has many attributes that define a shape’s style. You are probably already familiar with attributes such as display, visibility, font, and letter-spacing. SVG also has many SVG-specific styling properties (as in the example above, which shows how the stroke attribute allows you to define the color of the line).

SVG presentation attributes can help you quickly set the paint and geometrical values of SVG elements; apply gradients, filters, and clipping; and control the interactive behavior. Chapter 3, “Adding Text, Style, and Transforms” covers presentation attributes in more depth, but Table 2-1 provides a quick reference for common properties that you will be using in this chapter.

Table 2-1 Common SVG Presentation Attributes

Attribute

Values

stroke

This specifies the color of the stroke. The valid color values are the same as in CSS3 and HTML5: named color (e.g., “blue”), hexadecimal (e.g., “#f34a12”), RGB (e.g., “rgb(255,255,255)”), HSL (e.g., “rgb(100%,50%,90%)”),%), and so on. More detail about SVG colors can be found here: http://www.w3.org/TR/SVG/color.html.

stroke-width

This specifies the width of the stroke for a shape or text using either a percentage or a length value. When using a length value, we recommend specifying the type of unit (px, cm, etc.) to prevent cross-browser issues. It is worth pointing out that the units specified in the outermost <svg> tag are inherited by all descendants, and that the default value is px. You can find more details about possible length values here: http://www.w3.org/TR/SVG/types.html#DataTypeLength. Note that the stroke is centered on the edge of a shape, so if stroke-width is set to a large enough value, the shape’s fill may not even display.

stroke-opacity

This is a number between 1.0 and 0.0. A value of 1 makes the stroke entirely opaque and 0 makes it invisible.

stroke-dasharray

This is a list of user coordinate values (px) that determines the length or pattern of the invisible spacing to be drawn between segments along the stroke of text or a shape.

stroke-linecap

This defines the shape at both ends of a line. The options are butt (the default), round, and square.

stroke-linejoin

This determines the shape to be used at the corners of paths or basic shapes. The options are miter (the default), round, and bevel.

fill

This specifies the color of the shape or text.

fill-opacity

This is similar to the stroke opacity. Note that if the opacity is between 0 and 1, and the stroke value is set to a different color or opacity than the fill color, then the inner portion of the stroke will be a different color than the outer portion of the stroke, which can create some nice effects.

fill-rule

This determines which portions of a shape will be filled. The options are nonzero (the default) and evenodd. Note that this is usually straightforward, but for more interesting or complex shapes, the result of fill-rule can be less obvious, as explained in the “Fill Properties: nonzero and evenodd” section.

Rectangles

The rectangle element (<rect>) requires width and height attributes, but you can also specify x and y attributes, which specify the position in relation to the top-left corner of the SVG canvas. If they are not specified, they default to (0,0). Optional rx and ry attributes are also available, which apply a uniform rounding to all the corners. If only rx is specified, ry is equal to rx.

httpatomoreillycomsourcemspimages1261173.png
<rect x="50" y="50" width="300" height="170" rx="90" ry="50"
      stroke="darkseagreen" stroke-width="10"
      fill="lightgray" fill-opacity="0.6" />

Circles

As mentioned in Chapter 1, “Stepping into SVG,” the SVG <circle> element only requires a value for the radius. In the following image, the cx and cy values are set to (100,50).

httpatomoreillycomsourcemspimages1261175.png
<circle cx="150" cy="150" r="100"
        stroke="darkseagreen" stroke-width="10" fill="grey" fill-opacity="0.6"/>

Ellipses

The <ellipse> element provides the additional attribute ry so that both the x and y radius values can be set as shown below:

httpatomoreillycomsourcemspimages1261177.png
<ellipse cx="110" cy="55" rx="70" ry="35"
         stroke="darkseagreen" stroke-width="0.8"
  fill="lightgray" fill-opacity="0.6" />

Polylines and Polygons

There are just two additional basic shapes: the polyline and the polygon. They are very similar to each other in that they both simply require the points attribute, which contains a list of x,y value pairs. Both of these shapes allow for drawing a series of straight lines, as if a pen were set down and used to draw on paper.

The primary difference between the <polyline> and <polygon> shape elements in SVG is that the polyline path will not be closed by default—that is, the two endpoints will not be connected unless you specify that they should be. If you wish a polyline shape to be closed, you need to specifically draw an endpoint that meets back up with the starting point. The polygon, on the other hand, will automatically close the shape from the last specified point, as shown in this example:

// open
<polyline points="200,60 240,230 310,230 350,60"
          fill="lightcyan" fill-opacity="0.7"  stroke="darkviolet"
          stroke-width="25" stroke-linecap="round" stroke-opacity="0.2" />

// closed
<polygon points="100,50 115,120 150,150 115,180 100,250 85,180 50,150 85,120"
         fill="darkorange" fill-opacity="0.5" stroke="papayawhip"
         stroke-width="20" stroke-opacity="0.7" stroke-linejoin="miter"/>
httpatomoreillycomsourcemspimages1261179.png

Note how the stroke-linejoin and stroke-linecap attributes affect the shape.

Creativity with Basic Shapes

The beauty of the SVG language is that with just this basic knowledge, you are already able to start building some complex vector graphics that will render in all the major browsers. As an example, this next image demonstrates some of the fancy things that you can already do with a little creativity and knowledge of SVG shape properties.

This next example shows how the <line> element can be styled, with surprising results. All of the shapes on the left of the figure were created with a single <line> element, and all of the shapes on the right were created with just two <line> elements.

httpatomoreillycomsourcemspimages1261181.png

Even more interesting, the following minimalistic example demonstrates how to create fancy circular shapes using just one or two <circle> elements.

httpatomoreillycomsourcemspimages1261183.png

This third example uses only one or two <polygon> elements—again with interesting results:

httpatomoreillycomsourcemspimages1261185.png

I encourage you to open the code samples (see the Introduction for instructions on downloading the code samples) that come with this book to better understand how these interesting shapes were created. This will provide you with valuable insights into the workings of presentation attributes such as stroke, opacity, dash array, and others.

In addition to the basic shape elements, SVG provides the much more expressive <path> element, which allows you to create any type of two-dimensional shape.