Basic Shapes in SVG
Learn how to create basic shapes in SVG.
We'll cover the following...
It is time to dig into some code. We are going to learn how to create an SVG image. There are two ways we can create an SVG image. We can create a separate file for SVG images or create an SVG image inside an HTML document.
We are going to focus on adding SVG to our HTML documents. Unfortunately, the browser will limit some of the features of SVG if we try working with SVG files necessary for D3. It is much easier to work with SVG images in an HTML document.
Creating an SVG image
If you are working in a separate editor, create a plain HTML file with the following contents:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>SVG Example</title></head><body><svg></svg></body></html>
The code above is a regular HTML document. Creating an SVG image requires using the <svg>
tag. Most browsers support SVG images.
The <svg>
element is a container for all your graphics. The browser will look at this and know that you want to create an inline SVG image.
By default, the image will be empty. It is always good practice to set the dimensions of the image. We can set the dimensions with the width
and height
attributes.
<svg width="500" height="500"></svg>
The <svg>
element can be treated like a regular HTML element. You can apply classes, IDs, and even bind JavaScript events. It is one of the reasons why D3 recommends using SVG. Not only can they adapt to any size, but they can be easily modified to suit our needs. This flexibility will allow us to make our charts interactive.
In addition, we do not have to configure the dimensions directly on the element. We can configure the dimensions through CSS. We can see this in the following example:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>SVG Example</title><style>#container {width: 100%;height: 100%;}</style></head><body><svg id="container"></svg></body></html>