freeCodeCamp/guide/english/svg/shapes/index.md

81 lines
2.7 KiB
Markdown

---
title: SVG Shapes
---
## SVG Shapes
Several shapes can be created using SVG drawing. An SVG drawing can use and combine seven shapes: Path, Rectangle, Circle, Ellipse, Line, Polyline, and Polygon.
### Path
The `path` element is the most commonly seen, and is usually generated by programs designed to export SVG code.
```svg
<path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />
```
The example `path` above will generate a "plus" symbole (+) when used inside an SVG drawing. SVG `path` elements are not built manually, but generated through design programs that can manipulate vector graphics, such as Illustrator or Inkscape.
### Rectangle
The rectangle element `rect` draws a rectangle on the screen, and it accepts six attributes.
```svg
<rect x="0" y="0" width="100" height="50" rx="10" ry="10" />
```
`x` and `y` assign the position of the top-left corner of the rectangle, and `width` and `height` assign the size of the rectangle. `rx` and `ry` assign the radius of the rectangle corners, similar to the CSS border-radius property.
### Circle
The circle element `circle` accepts three attributes.
```svg
<circle cx="100" cy="100" r="50" />
```
`cx` and `cy` assign the position of the center of the circle, and `r` assigns the radius (size) of the circle.
### Ellipse
The ellipse element, `ellipse`, is similar to the `circle` element except the radius is split into two attributes.
```svg
<ellipse cx="100" cy="100" rx="50" ry="20" />
```
Again, `cx` and `cy` assign the position of the center of the ellipse, and now `rx` and `ry` assign the horizontal and vertical radius of the ellipse, respectively. A larger `rx` will give a "fat" ellipse, and a larger `ry` will give a skinnier ellipse. If `rx` and `ry` are equal, it will form a circle.
### Line
The `line` element is simple, and accepts four attributes.
```svg
<line x1="0" x2="100" y1="50" y2="70" />
```
The `x1` and `y1` attributes assign the first point of the line, and the `x2` and `y2` attributes assign the second point of the line.
### Polyline
A `polyline` is a series of connected straight lines, assigned in a single attribute.
```svg
<polyline points="0 100, 50 70, 60 40, 20 0" />
```
The `points` attribute assigns a list of points, each point separated by a comma.
### Polygon
The `polygon` element is also a series of connected straight lines, but in this case, the last line will automatically reconnect to the initial point.
```svg
<polygon points="0 100, 50 70, 60 40, 20 0" />
```
This example will draw the same shape as the `polyline` above, but it will draw an extra line to "close" the series of lines.
## More Information
MDN Documentation: <a href='https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Basic_Shapes' target='_blank' rel='nofollow'>MDN</a>