Programming Basics: A website for teaching people how to program
Do your programming with [jsbin] or [Orion]

Computer Graphics with HTML5 Canvas and JavaScript: Bonus Topic: Curves

I'll now be covering the optional topic of curves. With curves, you can draw more interesting shapes like circles or smiley faces.

In order to draw a curve, you need to tell the computer which curve you want to draw. Let's say you're making a rounded rectangle, and you have to draw a curve between these two straight lines. How do you tell the computer to draw a curve there?

To do that, you have to give the computers three points.

Once you give the computer these three points, it will draw a curve between them.

But which curve will it draw? Why did it draw this curve,

instead of this curve,

or maybe this curve? Aren't they all curves? How does the computer decide to draw this particular curve?

I'll now tell you how a computer draws its curve. Let's say you give the computer three points for a curve.

It first draws lines between these three points. Then, it divides the lines into equal sized chunks.

Here, we'll divide up this first line into five pieces.

And we'll divide up the other line into five pieces as well.

Then it draws a line between the first parts of each of the two lines.

Then it draws a line between the second parts of each of the two lines.

Then it draws a line between the thirds part of each of the two lines.

And then between the fourth parts of each of the two lines.

If you look at all these lines, you'll see that it makes a nice curvy shape. That's the curve that the computer draws when you give it three points.

Now that you know the process that a computer uses to draw curves, here is the program you have to type to actually get the computer to draw one.

First, like a line, you have to give a moveTo() command to tell the computer where you want to start drawing your curve.

Then you use this quadraticCurveTo command and give two sets of positions. The first two numbers refer to this point here 90, 20.

And then the next set of two numbers refers to the last point 100, 90.

Once you give this command, the computer will follow the steps we described before. It will draw lines between the points.

It will draw little lines there until it makes a curving shape.

Then when you call c.stroke() it will actually draw the line for the curve.

Why don't you try drawing your own curves now. Here is the code for drawing a curve and some ideas of things you can draw.

Do your programming with [jsbin] or [Orion]

Programming Basics

E-mail | About | Privacy Policy