Introduction to SVG in HTML5: Creating basic shapes
Tags: webdev, programming, beginners, tutorial
Published: 2023-12-26 20:29:35

Imagine logos that stay sharp on any screen, icons that zoom in without distortion, and animations that come alive with smooth, dynamic movement. 

All thanks to SVG, a language that builds graphics like tiny, flexible building blocks. No more blurry messes! 

With SVG, you get stunning visuals that adapt to any device, keep your website light and fast, and even open up the door to fascinating animations. 

It lets you add two-dimensional scalable vector graphics to your website. 
SVG has been around since 2001 and can be used in most modern browsers. It is supported by all major browsers and is easy to use. 

In this article, we will learn the introduction to SVG and how to create common shapes.


#What is SVG?
SVG stands for Scalable Vector Graphics, it is a web-based graphics language that allows developers to create and display vector-based images on the internet. Unlike raster images that are made up of pixels, SVG images are constructed using mathematical equations and are resolution-independent, making them scalable and adaptable to different screen sizes.

###Advantages of SVG
1.*Zoom in without Zoom Woes:* 
Unlike pixelated images that turn blurry when magnified, SVG graphics are built on math, not pixels! This means they stay sharp and crisp no matter how much you zoom in or out, making them perfect for logos, icons, and any element you want to look flawless on any screen.

![vector versus raster Google image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c00qoykkpbenlu6h1hsh.jpg) 

2.*Feature-Packed Playground:* 
SVG isn't just for basic shapes. It's a whole playground of graphical possibilities! From smooth curves and vibrant gradients to intricate patterns and cool filters, SVG lets you express your creativity and design stunning visuals that fascinate your audience.

3.*Edit Anywhere, Anytime:* 
No need for fancy software! You can create and tweak SVG graphics like a pro using code, simple text editors, or even design tools. This flexibility makes SVG accessible to everyone, from seasoned designers to code-curious beginners.


##How to get started
To get started with creating SVG graphics, you need to have a basic understanding of XML (eXtensible Markup Language) as SVG is an XML-based format. 

SVG code consists of a series of XML tags enclosed within an `<svg>` element which defines the dimensions and properties of the graphic.

###SVG basic shapes and their Attributes

1.**Circle** 
The `<circle>` element is used to draw a circle

- **cx and cy:** 
These are the coordinates of the center of your circle.

- `<cx>` This controls the horizontal position of the center (left or right). 

- `<cy>` This controls the vertical position of the center up(top) or down(bottom). 

- `<r>` This is the radius of your circle determining how big or small your circle appears.

- `<fill>` fill lets you fill your circle with any color you desire, (you can set it to "none" for an invisible circle using fill="transparent"). 

- `<Stroke>` This controls the color and thickness of the circle's outline, Similar to fill, you can set its color and thickness. stroke="red" stroke-width="2" would give the circle a red outline with a thickness of 2 pixels.

- `<Opacity>` This determines the transparency of the circle.
 A value of 1 is fully opaque (solid), while 0 is completely invisible. 

- `<visibility>` This simply lets you hide or show the circle. visibility="visible" turns the circle on, while visibility="hidden" turns it off.

- `<class>` This helps you group and style circles easily. 

*Now let's create an SVG graphic that displays a circle:*

``` XML
<svg width="1000" height="1000">

<circle cx="150" cy="250" r="25" fill="green" stroke="purple" stroke-width="5" opacity="5" />
    
    <circle cx="200" cy="100" r="40"
stroke="green"
 stroke-width="3" fill="red" />
           
<circle cx="100" cy="100" r="50" fill="yellow" stroke="red" stroke-width="1" opacity="6"/>
</svg>
```
*Output*
![Image of a circle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vk0khwxmuiiu87y3aeiu.jpg)

2.**Ellipse**
The `<ellipse>` element is used to draw an ellipse.

Circles and ellipses share many similarities in their SVG attributes, making them powerful tools for creating diverse shapes. Here is a breakdown

**Positioning and Visibility:**

- `<x>` & `<y>`
Both use these attributes to define the position of their center point in pixels, allowing you to place them anywhere on the canvas.

- `<visibility>`
Both utilize visibility="visible" and visibility="hidden" to control whether they appear or are hidden from view.

- `<fill>` 
Both use fill to define the color of their interior, offering the same flexibility with color names and hex codes.

- `<stroke>` & `<stroke-width>`
Both use these attributes to control the color and thickness of their outline, allowing for consistent border styling.

- `<opacity>`
Both use opacity to adjust their transparency, enabling fading and layering effects.

- `<class>` 
Both support the class attribute for grouping and styling multiple elements together, simplifying your design workflow.

**Additional Similarities:**
 Both attributes use pixels as units for dimensions and positions.

###Key Differences:

- 
*Shape definition:*
 Circles use the r attribute for their radius, defining a perfectly round shape. Ellipses use `<rx>` and `<ry>` attributes for their horizontal and vertical radii, creating oval shapes with varying degrees of elongation.

- 
 *Focus:*
 Circles offer simplicity and consistency in their shape, while ellipses provide more flexibility for creating diverse oval shapes.

**Choosing between them:**
If your design needs a perfectly round shape, a circle is the ideal choice.
If you require oval shapes with varying degrees of elongation, an ellipse is the better option.

**Let's create an ellipse**
Example code:

``` XML
<svg width="1000" height="1000">
  <ellipse cx="100" cy="50" rx="80" ry="30" fill="blue" />
      
      <ellipse rx="50" ry="40"cx="300"
cy="50" fill="brown" stroke="green" stroke-width="5"/>
</svg>
```

*Output*
![Image of ellipse](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjfqoljnayu4yqc12gwc.jpg)

3.**Rectangle `<rect>`**
The rectangle element lets you draw and style the shape of a square or rectangle
Both can be combined with CSS for further styling and customization.

- `<x>` & `<y>`
These tell your square where to stay on the screen. Just like the corners of a sticky note, x being left-right and y being up-down. Both use numbers like "50" for pixels, so x=50 y=100 puts your square 50 pixels right and 100 pixels down.

- `<x>` 
Where the left side of the shape starts 

- `<y>`
 Where the top of the box starts 

- `<width>` 
How wide the box stretches (like arms reaching out)

- `<height>` 
How tall the box stands (like a proud giraffe!)

- `<fill>` 
The color inside the box (like painting its walls!)

- `<stroke>` 
The color of the box's outline (like drawing its frame)

- `<stroke-width>` 
The thickness of  the box's outline (think of a thin line or a bold border)

- `<visibility>`
The box can be set to be  seen or hidden 

**Special features**
- `<rx>` & `<ry>`
These are rounded corners like knobs that control how curvy the shapes are!

- `<class>`
 This makes it easy to group and style similar boxes together

**Let's create a simple SVG graphic that displays a rectangle:**

*Example code:*

``` XML
< svg width="1000" height="1000">
  <rect x="250" y="20" width="80" height="60" fill="green" />
      
    <rect x="150" y="200" width="200" height="100" fill="yellow" stroke="purple" stroke-width="2"/>

<rect width="100" height="100" x="70" y="10" stroke="green" stroke-width="4" rx="30"/> 

</svg>
```

*Output*

![Image of a rectangle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv8lte3ykdtnikp86ens.jpg)

4.**Line:**

Lines form connections, borders, and even intricate patterns. 

- 
`<x1`> & `<y1>`: These mark the starting point of your line, with x1 controlling the horizontal position (left-right) and y1 controlling the vertical position (up-down). 

Both use pixels as units, so x1="50" y1="100" places the starting point 50 pixels to the right and 100 pixels down from the top left of your SVG canvas.

- 
`<x2>` & `<y2>`: These define the ending point of your line, Similar to x1 & y1, they control the horizontal and vertical position of the ending point, allowing you to stretch your line in any direction.

- 
`<stroke>`: This is your virtual paintbrush for the line's color. Just like filling a bucket, you can choose any color name or hex code. For example, stroke="red" paints the line red, while stroke="transparent" makes it invisible.

- 
`<stroke-width>`: This is like the color of your pen for drawing the line. Similar to filling a shape, you can choose any color name or hex code. For example, stroke="blue" would draw a blue line, while stroke="transparent" would make it invisible! It also uses pixels, so stroke-width="3" makes your line 3 pixels thick.

- 
`<stroke-linecap>`: This determines the shape of the ends of your line, like the tip of your pen. The options are:

- 
`<butt>`(flat-ends): The default, where the line ends abruptly (like a blunt pen).

- 
`<round>`(curved-ends): Creates rounded caps, giving a softer look.

- 
`<square>`(boxy ends): Makes the ends square, like a chiseled pencil tip.

- 
 `<stroke-dasharray`: This lets you add dashes and gaps along the line, like dotted lines or musical notes.
You can specify the lengths of dashes and gaps in pixels, separated by commas. For example, stroke-dash array="5, 10" would create a line with alternating dashes of 5 pixels and gaps of 10 pixels.

- 
 `<stroke-dashoffset>`: This shifts the starting point of the dash pattern, like adjusting the first note in a melody. A value of 0 starts with a dash, while higher values move the pattern to the right, revealing more of the line before the first dash.

- 
`<opacity>`: This is the fading slider for your line, letting you control its transparency. A value of 1 is fully opaque (solid), while 0 makes it completely invisible. 

- 
`<visibility>`:visibility="visible" makes it appear, while visibility="hidden" sends it to the background.

- 
 `<class>`: This is your organizational tool, grouping your lines for easy styling. Assign a class like "borders" or "guidelines" to your line elements, and then style them based on class

**Let's create line shapes**

*Example code:*
``` XML
<svg width="500" height="500">
  <line x1="10" y1="10" x2="90" y2="90" stroke="violet" stroke-width="3"/>

<line x1="10" y1="250" x2="10"
y2="400" stroke=" blue" stroke-width="6"/>

<line x1="10" y1="250" x2="200"
y2="250" stroke="black" stroke-width="4"/>

</svg>
```

*Output*
![Image of a line](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fukfiklg1oo7zquz6o1c.jpg)

5.**Path:**

The <path> element is used to draw more complex shapes using path data.

Path element in SVG is incredibly powerful, allowing you to create an infinite variety of shapes and lines with just one element. However, its flexibility comes with a set of attributes that can seem overwhelming at first. Let's break down the main ones:

####Path Data:

- 
`<d>`: This defines its shape with a series of path commands and coordinates. These commands tell the path how to move, draw lines, curves, and more. It's a bit like giving directions on a map, telling the path where to go and what shapes to make.

`<M>`: This command marks the starting point of the path. You can use multiple M commands to create a path with multiple segments.

`<L>`: This command draws a straight line to the specified coordinates.

`<C>`: This command creates a curve by defining two control points and the ending point. Imagine pulling a rubber band between these points, and that's the shape of the curve.

`<Z>`: This command closes the path by drawing a straight line back to the starting point of the last subpath.

**Other Attributes:**

`<fill>`: Similar to other SVG elements, you can define the interior color of the path with fill.

`<stroke>`: This defines the color and thickness of the path's outline using stroke and stroke width.

`<stroke-linecap>` & `<stroke-linejoin>`: These control the appearance of the path's ends and corners, offering options like "butt", "round", and "miter" for a variety of styles.

`<opacity>`: Adjusts the path's transparency, making it partially visible with values between 0 and 1.

`<visibility>`: This simply shows (visible) or hides (hidden) the path.

`<class>`: Just like other elements, you can assign a class to a group and style multiple paths together for easier management and consistency.

*Example code (drawing a path):*

``` XML
<svg width="1000" height="1000">
  <path d="M10 80 L90 80 L50 10 Z" fill="green" />

<path d="M 100 50 L 50 300 L 200 300 z" fill="red"/>
    
    <path d="M 200 50 H 400 z" fill="red" stroke="ash" stroke-width="4"/>

<path d="M 200 50 V 400 z" fill="none" stroke="orange" stroke-width="4"/>

<path d="M 200 50 C 180 200, 200 200,400 104 z" fill="none" stroke="black" stroke-width="5" />

<path d="M 200 50 S 180 200,400 104 z" fill="none" stroke="pink" stroke-width="3"/>
            
<path d="M 200 50 Q 180 200,400 104 z" fill="none" stroke="yellow" stroke-width="5"/>

<path d="M 200 50 Q 180 200,400 104 z" fill="purple" stroke="gold" stroke-width="5"/>

<path d="M 200 50 Q 180 200,400 104 T 400, 200  z" fill="pink"
stroke="green" stroke-width="5"/>
</svg>
```
 
*Output*
![Image of a path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o12e9aw1fi2a3cahwe4b.jpg)

6.**Polygons:**
The <polygon> element is used to draw closed polygons (shapes with straight sides), letting you create an array of shapes from triangles to stars and beyond. 

However, understanding their attributes is crafting precise and visually stunning creations.

**Attributes**
- 
 `<points>`: This is the blueprint of your polygon, a list of coordinates (x,y pairs) defining its vertices (corners). 

It's like connecting dots on a grid – each coordinate tells the polygon where to turn and how far to travel. The more points you list, the more complex your shape becomes!

- 
`<fill>`: This is your virtual paintbrush, filling the polygon's interior with any color you desire. You can use names like fill="blue" or hex codes like fill="#ff0000" for fiery red. You can even make it invisible with fill="transparent"!

- 
`<stroke>`: Imagine this as the border of your polygon, like the rim of a plate. stroke lets you control its color and thickness. Just like fill, use stroke="green" stroke-width="2" to give your polygon a green outline 2 pixels thick.

- 
`<stroke-linecap>` & `<stroke-linejoin>`: These refine your polygon's edges. stroke-line cap determines how the ends of your polygon lines look (butt, round, or square), while stroke-line join controls how corners between lines are formed (miter, round, or bevel). They add finesse to your shapes!

- 
`<opacity>`: This is the fading slider for your polygon, letting you control its transparency. A value of 1 is fully opaque (solid), while 0 makes it completely invisible. 

`<visibility>`: This is the on/off switch for your polygon. visibility="visible" makes it appear, while visibility="hidden" sends it to the background, like a magician's vanishing act.

- 
`<class>`: This is your organizational tool, grouping your polygons for easy styling. Assign a class like "shapes" or "icons" to your polygon elements, and then style them based on that class. 

*Example code (drawing a triangle and a star):*

``` XML
<svg width="1000" height="1000">
  
  <polygon points="10 80, 90 80, 50 10" fill=="green" />

<polygon points="500,200 400,400 650,280 350,280 600,400" fill=" gold" stroke="pink" stroke-width="3" fill-rule="even even"/>
</svg>
```
*Output*
![Image of a polygon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uya98ypsqbo5efksp29w.jpg)

7.**Polyline:**
The <polyline> element is used to draw open polygons (shapes with straight sides).
They are like versatile artists – they can draw simple lines, complex shapes, and everything in between. 

**Attributes**

- 
`<points>` (required)
 This is the blueprint of your polyline, a list of coordinates (x,y pairs) defining the points it visits on its journey. Imagine it like connecting dots on a grid – each point tells the polyline where to turn and how far to travel. The more points you list, the more complex your line becomes!

- 
`<fill>` (optional)
 While not commonly used with polylines (they're primarily for outlines), you can use fill to color the area enclosed by the polyline if it forms a closed shape. Think of it like filling in a coloring book page but with lines instead of outlines.

- 
`<stroke>`
 (required by default): This is the color and thickness of your polyline's outline, like the pen you use to draw it. stroke lets you choose any color you want, and you can control the thickness with stroke width. For example, stroke="red" stroke-width="3" would give you a thick red line.

- 
`<stroke-linecap>` (optional): This determines how the ends of your polyline look. Choose from "butt" (square ends), "round" (curved ends), or "square" (extended square ends) to add a stylistic touch to your line's beginning and end.

- 
`<stroke-linejoin>` (optional): This controls how corners between the line segments of your polyline are formed. Choose from "miter" (sharp corners), "round" (smooth corners), or "bevel" (angled corners) for a customized look at the joints.

- 
`<opacity>` (optional): This is the fading slider for your polyline, letting you control its transparency. A value of 1 is fully opaque (solid), while 0 makes it completely invisible. Play with values between 0 and 1 to create subtle or dramatic fading effects, like a line slowly emerging from the mist.

- 
 `<visibility>` (optional): This is the on/off switch for your polyline. `<visibility="visible>` makes it appear, while `<visibility=" hidden>` sends it to the background, like a magician's disappearing act.

- 
`<class>` (optional): This helps you group and style polylines easily. Imagine labeling all your red lines with "error" or all your green lines with "success". You can assign a class and then style them based on that class, saving you time and effort.


**Example code (drawing a zigzag line):**

``` XML
<svg width="1000" height="1000">
    
  <polyline points="10 20, 40 60, 70 20, 100 70" fill="none" stroke="green" stroke-width="6" />
      
<polyline points="20,700 400,750 150,800,250 1000" stroke=" purple" stroke-width="4" fill="none"/>
    
</svg>
```

![Image of a polyline zigzag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5lxzbbia5mkjs8d1vt2.jpg)

7.**Text**
SVG text elements offer incredible flexibility for adding words and phrases to your visuals. 

- 
`<x>` & `<y>`
 These define the position of the text's baseline (the line where the bottom of letters sit). Imagine them like anchor points, with x controlling the horizontal position (left-right) and y controlling the vertical position (up-down). Both use pixels as units, so x="50" y="100" places the baseline 50 pixels to the right and 100 pixels down from the top left of your canvas.

- 
`<dx>`& `<dy>`
 Think of these as fine-tuning knobs for the text's position. They allow you to nudge the baseline slightly after setting x and y. dx shifts left-right, while dy shifts up-down. Both use pixels as units, so dx="5" dy="-2" would move the text 5 pixels to the right and 2 pixels down from the initial position.

- 
`<text-anchor>`
 This determines the alignment point for the text relative to the x and y coordinates. Think of it like a flagpole for your text. The options include:

`<start>`
 Align the text's left edge with the x coordinate.
middle: Centers the text horizontally around the x coordinate.

`<end>`
 Align the text's right edge with the x coordinate.

Other options like inherit and specific x/y offsets are also available.

- 
`<font-family>`
 This specifies the typeface of your text. Choose from installed fonts on your system or use web fonts for wider options. Use names like "Arial" or "Roboto" or specify font families with quotes (e.g., "Open Sans Condensed").

- 
`<font-size>` 
This controls the text height in pixels. A larger value makes the text taller, while a smaller value makes it shorter. Remember, readability is key!

- 
`<font-weight>`
 This defines the boldness of the text. Choose from options like "normal," "bold," "lighter," or even specify a numeric weight (e.g., "font-weight: 500").

- 
`<fill>` This is your virtual paintbrush for the text, just like for shapes. Use color names or hex codes to make your words stand out. You can even use fill="transparent" to create invisible outlines!

- 
`<stroke>` & `<stroke-width>` Similar to fill, these define the color and thickness of the text's outline. Use them to create borders around your words or add decorative accents.

- 
`<opacity>`
 This controls the transparency of the text, allowing you to fade it in or out. A value of 1 is fully opaque (solid), while 0 makes it completely invisible.

- 
`<visibility>`
 This is the on/off switch for your text. visibility="visible" makes it appear, while visibility="hidden" sends it off-screen like a disappearing act.

Code
``` XML
<svg>
<text x="50" y="50" fill="brown"> SVG <tspan x="50" y="70">   shapes </tspan> <tspan  x="50" y="90"> basic </span />
</svg>
```
Output

![Image of text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nn9aiw94umkcg4yv78s1.jpg)

Note: You can decide to style using CSS.

####Additional Resources:

SVG Text Attributes: [mozilla](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text)

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text

CSS Text Properties: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_text


###Conclusion 
SVG is a powerful graphics format that enables developers to create visually stunning graphics that can be scaled and adapted to different screen sizes. By using SVG code snippets, developers can have precise control over the appearance and behavior of their graphics.
By combining these elements and utilizing various attributes and styles, you can create complex and customized graphics.