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

Computer Graphics with HTML5 Canvas and JavaScript: Colored Lines

I previously showed you how to make simple black lines, but colored lines make it easier to draw certain things.

First, let's review how to draw simple black lines. In order to draw a line,

you first move your pen to somewhere

you then use the lineTo() command to tell the computer that you want to draw a line somewhere

and then you use the stroke() command to tell the computer to actually draw the line.

If you want to draw a colored line, you use this new command. You type c.strokeStyle, equals, and then a color you want to use. Here, we'll use the color red.

When you put a c.strokeStyle='red' command before a c.stroke() command, the line you draw will be red.

You aren't limited to red either. You can use all sorts of colors like black, blue, brown, green. Here's a list of several different colors available to you.

One weird thing happens though if you try to draw two lines of different colors.

Let's say you start by drawing a green line. Here you move somewhere, you use lineTo() to say you want to make a line somewhere, you use strokeStyle to say you want the line to be green, and then you use stroke() to actually draw this green line.

Then let's say you want to have a red line too. So you use moveTo() to move somewhere else, you use lineTo() to tell the computer to draw a line, strokeStyle to say that you want the line to be red, then you use c.stroke() to actually draw the line. You think you'd have two different lines: a green line and a red line.

But you actually end up with two red lines. What happens is that the c.stroke() command tells the computer to go to the places where you said you wanted lines and actually draw lines there. The problem is that the computer goes right to the start of the program and draws all of your lines in red. Even though you already drew this line in green, it will draw over it again using red. That's why you end up with two red lines.

But, you don't want the computer to go back to the start of the program. You only want the computer to draw this last line in red. To do that, you need a new command called c.beginPath(). This tells the computer to start a new line. Afterwards, when you use c.stroke(), the computer will only draw the lines from after the c.beginPath().

So why don't you try out these colored lines now? Here are some ideas you might want to try out like mountains or houses or deer. Go ahead and give it a try.

Do your programming with [jsbin] or [Orion]

Programming Basics

E-mail | About | Privacy Policy