Using polygon to Render Rectangles

   



Using path to Render Rectangles

The SVG path element is extremely powerful and it can be used for rendering many geometric objects, including rectangles. This element is useful for defining complex graphics images that contain curvilinear components. Defining a rectangle by means of this element is useful in situations (e.g., animation) where you need to modify the vertices of the rectangle in order to render a quadrilateral or a parallelogram, or perhaps collapse the rectangle into a line segment.

The SVG document in Listing 1.4 uses the SVG path element in order to render a rectangle.

Listing 1.4 rect3.svg

start example
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN"  "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd"> <svg width="100%" height="100%"> <!-- draw rectangle --> <g transform="translate(50,50)"> <path  d="M0,0 150,0 150,50 0,50"  style="fill:red;"/> </g> </svg>
end example

Remarks

The SVG path element is more general than the SVG polygon because it can be used to specify curved components in addition to line segments, which makes the SVG path element incredibly flexible and versatile.

Notice the syntax of the points in a path:

d="M0,0 150,0 150,50 0,50"

The preceding path definition can be translated as follows: 'move to the point (0,0); draw a line segment from the point (0,0) to the point (150,0); draw a line segment from the point (150,0) to the point (150,50); draw a line segment from the point (150,50) to the point (0,50).'

Note that if you inadvertently specified the following line,

 d="0,0 150,0 150,50 0,50"

you will see this error message in the lower corner of your browser:

path data missing a moveto

The uppercase M refers to an absolute point. You can use a lowercase m if you need to specify a point in the plane that is relative to the preceding point (i.e., the point that is to the immediate left of the current point).

The same logic applies to uppercase L and lowercase l when rendering line segments. For example, the following snippet,

 d="M100,0 L150,0 150,50 0,50"

starts with a line segment from (100,0) to (150,50), whereas the snippet,

d="M100,0 l150,0 150,50 0,50"

starts with a line segment from (100,0) to (250,0).

The reason for the difference is because L150,0 specifies an absolute point, regardless of the value of the preceding point. On the other hand, l150,0 is relative to the absolute preceding point M100,0. Adding the two x-coordinates and the two y-coordinates of M100,0 and l150,0 yields the point (250,0).



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net