Background

SVG’s contain many different types of child elements, including circles, ellipses, and linear paths.

Objective

In this tutorial, we will use the circle we created in the previous post and make it into a face.

Process

Step 0: Recap

In our last tutorial, we drew a circle with properties separated into CSS.

 
  
 
 
 
 svg {
   width: 150px;
   height: 150px;
   background-color: #EEEEEE;
 }
 circle {
	fill: #95D6F1;
	stroke: #000000;
	stroke-width: 2;
 }
 
 

Step 1: Add the eyes

We will use ellipses for the eyes. Like circles, ellipses have cx and cy attributes that determine where they show up. But while circles have one radius, determined by r, ellipses have two radii — a vertical one, ry, and a horizontal one, rx. I am making ry larger than rx because I want “tall” ellipses for these eyes.

Here is the HTML code. (The CSS is the same as before.)

	
		
	

Step 2: Add the mouth

I want the option of a curved mouth, so to draw this one, I am going to use the path element. Here is how it will look:

The path element has three attributes we are familiar with:

  • fill, which we will set to “transparent”
  • stroke, which we will set to #000000”
  • stroke-width, which we will set to 2

But in addition, there is a new property to set, which determines the length and curvature of the path. This is known as d. This is what the code snippet will look like for the path with d incorporated.

	
		
	

Chris Coyier wrote a terrific tutorial on the d attribute that I encourage you to take a look at. While I will not be covering the d attribute in nearly as much depth, I wanted to discuss the commands used in my example.

Each letter in the d attribute is a command, and each command has a set of arguments that are passed into it. For instance, the M value has 42,85 passed into it.

Let’s take a closer look at this d attribute’s two commands.

  • M42,85: the M refers to “moveTo”; in other words, where you “move” the pen before you put it down to draw. In this case, we are moving it to coordinates 42,85</code.
  • Q73,141 103,85: This is a quadratic curve control point. Its first point is used to a bezier point used to control the line’s curvature; the second point, 103,85, is the right side of the smile.

There are bezier curve generators out there that you can use to generate code like this. Here is one of them that I used to generate the mouth.

SVG Quadratic Curve Example, blogs.sitepoint.com

You can also draw cubic curves with the Ccommand. As a follow-up exercise, you could try to replace the quadratic curve command with a cubic curve command. Here is another generator from SitePoint that you may find helpful.

SVG Cubic Bézier Curve Example, blogs.sitepoint.com

Next up

In our next few tutorials, I will go over how to adjust the face expression wtih different SVG techniques and how to make the face change expressions with the click of a mouse.