HTML SVG Basics
The svg element holds a drawing built from shape elements. SVG is short for Scalable Vector Graphics.
A circle
The circle element draws a round shape. The r value sets the radius. A radius is the distance from the centre to the edge.
<svg width="200" height="120">
<circle cx="60" cy="60" r="40" fill="green"></circle>
</svg>A rectangle
The rect element draws a rectangle. The x and y values set the top left corner. Width and height set the size of the rectangle.
<svg width="200" height="120">
<rect x="10" y="10" width="100" height="60" fill="blue"></rect>
</svg>A line
The line element runs from one point to another. Stroke sets the colour of the line itself.
<svg width="200" height="120">
<line x1="10" y1="100" x2="190" y2="10" stroke="black"></line>
</svg>Words inside a drawing
The text element writes words inside a drawing. Its x and y values set where the words start.
<svg width="200" height="120">
<text x="20" y="60">Home</text>
</svg>Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>A Small House</title>
</head>
<body>
<h1>A Small House</h1>
<p>The drawing below is made from shape elements.</p>
<svg width="220" height="160">
<circle cx="180" cy="30" r="20" fill="yellow"></circle>
<rect x="40" y="70" width="100" height="70" fill="brown"></rect>
<line x1="30" y1="70" x2="90" y2="30" stroke="black"></line>
<line x1="90" y1="30" x2="150" y2="70" stroke="black"></line>
<text x="60" y="100">Home</text>
</svg>
<p>The sun, the house, and the word Home are all shapes.</p>
</body>
</html>Key points
- svg: an element that holds a drawing built from shape elements
- fill: the colour inside a shape
- stroke: the colour of a line or a shape outline
- Shapes draw in the order they are written
- A later shape can cover an earlier one
In this example, the heading and paragraph introduce the drawing. The svg element holds a circle for the sun and a rectangle for the house body. Two line elements form the roof. The text element writes the word Home inside the house. The last paragraph names the shapes in the drawing.
Note
SVG draws with shape elements. Canvas draws with script steps.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which element draws a circle inside an svg element?