Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

# SVG Basics – Shapes

Basic SVG Shapes

SVG defines 5 basic shapes. These shapes all have attributes specific to that shape for positioning and sizing. They also each have presentation attributes which effect things like fill and stroke color, border width and more. Basic shapes (and complex shapes) have many common presentation attributes.

The ‘rect’ Element
<rect x=”20″ y=”20″ rx=”0″ ry=”0″ width=”160″ height=”160″ fill=”blue” />
Code 1. Rectangle

The ‘circle’ Element
<circle cx=”100″ cy=”100″ r=”90″ fill=”blue” />
Code 2. Circle

The ‘ellipse’ Element
<ellipse cx=”100″ cy=”100″ rx=”90″ ry=”80″ fill=”blue” />
Code 3. Ellipse

The ‘line’ Element
<line x1=”10″ y1=”10″ x2=”190″ y2=”190″ stroke=”blue” stroke-width=”4″ />
Code 4. Line

The ‘polyline’ Element
<polyline points=”10,190 20,190 20,150 50,150 50,190 80,190 80,110 110,110 110,190 140,190 140,70 170,70 170,190 190,190″ stroke=”blue” fill=”darkblue” stroke-width=”4″ />
Code 5. Polyline

The ‘polygon’ Element
<polygon points=”100,10 40,180 190,60 10,60 160,180 100,10″ stroke=”blue” fill=”darkblue” stroke-width=”4″ fill-rule=”nonzero” />
Code 6. Polygon

The difference between the polygon and the polyline is that polygons are a closed shape. If the last and first polygon points don’t match then the shape is closed automatically.

Clip and fill rules (clip-rule & fill-rule)

Polygons, polylines and clipping planes all use either the rule ‘evenodd’ or ‘nonzero’ to determine where the inside of an object is. Both rules work by starting with a count of 0 and fill sections based on this count. This count changes when a ray intersects with a line segment of the graphic element being filled.

The nonzero rule (default) works by taking a ray from inside the graphic element and going outside to infinity. At each intersection point of the ray and the line/curve segments of the graphic element you compute the slope and rotate it 90 degrees counterclockwise. A vector pointed in the same direction of the ray (dot product > 0) adds 1 to the count and one in the opposite direction (dot product < 0) adds -1. A final number which is not zero results in the filling of that point.

The evenodd rule works by taking a point in the shape and counting the number of times a ray from that point to infinity crosses the line/curve segments of the graphic element. An odd count means the point is inside the shape. In both cases, if the polyline or path is not closed (start and end points have the same x and y coordinates) it is automatically closed to compute the interior segments of the shape.