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

Computer Graphics with HTML5 Canvas and JavaScript: Lines

So you've now typed up a small program that draws a line. But what exactly is going on? How does this program work?

The program uses something called a canvas for doing drawing. A computer canvas is like a painting canvas. It's like having a blank piece of paper to draw on. Now imagine that the computer has a pen for drawing on this paper. To draw on the paper, you give commands to the computer about where to put the pen and where to move it on the paper.

In your program, the first command is c.moveTo(20, 90). The c is for canvas, moveTo tells the computer that you want to move the pen somewhere, and 20,90 is the position where you want the pen. Remember how you tell a computer about which pixels you want to change. You start in the upper-left. 20 is how far you want to move to the right, and 90 is how far you want to move down. That is where you want to move your pen to at the beginning.

c.lineTo() tells the computer that you want to draw a line somewhere. That 90, 90 gives the position where you should move your pen while drawing the line. Remember, to find 90,90, you start in the upper-left, then go 90 to the right, and then 90 down. In the first line of the program, you moved the pen to 20, 90 here, and in this second line, you are telling the computer that you want to draw a line going to this new position 90, 90.

Finally c.stroke() tells the computer that you actually want to draw the line now. Previously you just said where you wanted the computer to draw a line, but the computer didn't actually draw it. With c.stroke(), the computer will then draw a line over the places where you told it you wanted a line.

So by telling the computer where to move its pen and where you want to draw lines, you can get the computer to draw some fairly interesting pictures for you. Here we have a program for drawing a little house.

Let's go through the program line by line.

First, we move to a position.

We then tell the computer about the different lines that make the basic outline of a house.

Then we move to the bottom in order to draw a door.

Then we tell the computer about the lines that make up the door.

And then finally we use c.stroke() to tell the computer to actually draw these lines now.

Now that you know how to draw lines on a computer, why don't you try making some simple pictures. Here are some ideas you can try. Try drawing a square, or a little stick figure, or even a neat 3d shape using lines.

Do your programming with [jsbin] or [Orion]

Programming Basics

E-mail | About | Privacy Policy