It's a good idea to download the code for this exercise before you start.
In our first script we drew some text and a shape; now let's create more shapes.
First, just as we did with our Hello World exercise, create an HTML page in Dreamweaver. Inside the body tag, add a Canvas tag and a script tag that points to a new JavaScript file named draw-shapes.js. This page looks a lot like the first HTML page we created—the only difference is the title tag (I gave my page a title of Draw Shapes) and the src for the script (I'm pointing to a new file called draw-shapes.js).
The code looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Draw Shapes</title>
</head>
<body>
<canvas id='myCanvas' width='1200' height='800'>
You'll need a contemporary browser with javascript
turned on to be able to see this page
</canvas>
<script src='draw-shapes.js'></script>
</body>
</html>
Save your html file with a decriptive name—I called my HTML file draw-shapes.html. (Don't forget the naming conventions for files you plan to upload to the internet.)
Next, create a JavaScript file in Dreamweaver and add comments to the top of the file to describe the code.
//Draw Shapes
//Draw squares, circles, and triangles
Add the two lines of code that create the canvas tag and graphic context.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
In a moment we'll draw some squares with a context method called rect(). Before we do that, we'll set the color of the shape's outline with this code:
context.strokeStyle = '#158ad4';
strokeStyle is a property of the object context, Canvas' graphics layer. We're setting strokeStyle to a hexadecimal number.
The hexadecimal numeral system counts in blocks of 16; it's base 16. The numbers in this system start at 0, go up to 9, and then 10, 11, 12, 13, 14, and 15 are represented by a, b, c, d, e, and f. If we wanted to represent the base-10 number of 24 in hexadecimals, we'd write is as 18—1 block of 16 and 8 digits which together add up to 24 in base 10.
In digital media, we use hexadecimals to represent color values. Digital screens paint with red, green, and blue light. Every color you see on a screen is some combination of those three colors. Look again at the hexadecimal value in our line of Javascript code—#158ad4. The hashtag tells the browser that this is a hexadecimal number. After the hashtag, you have six numbers. The first two numbers determine the value of your reds, the next two, your greens, the last two, your blues.
So our red color value is 15—1x16 + 5 = 21 in base 10. Our green is 8a—8x16 + 10 = 138 (remember hexadecimal a is 10 in base 10). Our blue is d4—13x16 + 4 = 212. Each color has a total of 256 values in base 10, starting at 0 and ending at 255. The range in hexadecimals starts at 00 and ends at ff.
The higher the value, the brighter the color will be. A value of 00 for blue, for example, would be completely black (we're assuming here that the other colors, red and green, are valued at 00 as well—our three pairs of hexadecimals look like this: #000000); a value of ff (the highest value for this color system, ff = 15x16 + 15 = 255) would be a bright, intense blue (#0000ff).
Over time, you get a feel for hexadecimal values and can guess the color a value represents. But an easier way to pick colors and get their hexademical values is to go into Photoshop, open the Color Picker (double click on the Tool panel's color box), slide the Color Slider to the hue you want and select the saturation and brightness from the Color field on the left. When you have the color you want, you'll notice on the Color Picker's right hand side that Photoshop gives you a range of numerical values: Hue, Saturation, and Brightness; Red, Green, and Blue; and ahexadecimal value at the bottom. Copy and paste the hexadecimal number into your JavaScript code to set your color values.
Back to the code. When we left off, we set our context's strokeStyle property to a blue color. Don't forget to surround the hexadecimal value with quotes like this:
context.strokeStyle = '#158ad4';
Now we need to create our squares. Here's the code to create three squares in a row:
context.rect(440, 40, 100, 100);
context.rect(560, 40, 100, 100);
context.rect(680, 40, 100, 100);
context.stroke();
These three lines call the same context method—rect(). The rect() method creates a rectangle or square shape depending on the arguments you pass to it. It takes four arguments, the first two are X and Y position, the shape's top left corner is placed at this position. The last two arguments are the shape's width and height. We're creating squares because each shape has the same 100x100 pixel width and height. The squares are placed in the center of the canvas, 40 pixels from the top, and 20 pixels apart.
To draw the squares, type this line of code:
context.stroke();
Stroke() is a context method that draws the outline of a shape.
The code so far looks like this:
//Draw Shapes
//Draw square, circles, and triangles
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.strokeStyle = '#158ad4';
context.rect(440, 40, 100, 100);
context.rect(560, 40, 100, 100);
context.rect(680, 40, 100, 100);
context.stroke();
Save your javascript file—I named my file draw-shapes.js. Give your JavaScript file the same name you reference in the script tag's src in your HTML page. Open your favorite browser and then open your HTML file in that browser (With your browser open, press Cmd + o on a mac or Ctrl + o on a PC to open your file.) Hopefully you see three blue outlined square in a row.
If you don't see squares, open your Console window and see if you have any error messages. If you have no error messages, go back to your code and compare it to the code here. Fix any mistakes, refresh your HTML page in your browser, and hopefully the code works.
I recommend writing a little code and then testing it out. If something's not working, fix the bug before you add more code. I don't recommend typing a lot of code and checking it only when you're done. Check as you go so that you don't replicate mistakes and you solve your problems as you build your code. Code a little, test it, fix it, and then continue to code.
If you want to create more complex shapes, you'll need to create a path and then fill its inside or stroke its outline with color. Think of a path as an outline of a shape. If you've used Illustrator, the vector graphics in that program are created by drawing a series of points. You can stroke the points to create a line. Or you can close your path—connect your end point to your start point—and fill the path with a color to create a shape. The paths you create in Canvas are similar to the ones in Illustrator.
Here's some code to create three solid red circles:
context.fillStyle = '#e22011';
context.beginPath();
context.arc(490, 240, 50, 0, 2*Math.PI);
context.arc(610, 240, 50, 0, 2*Math.PI);
context.arc(730, 240, 50, 0, 2*Math.PI);
context.fill();
fillStyle is another property of context. It determines the color of the shapes you draw. We've set it to a red hexadecimal color.
The beginPath() method tells the browser to start up a new path. The arc() method creates an arc based on radians—radians measure angles, they're like degrees but have a different measurement unit. 180 degrees is equivalent to PI radians (approximately 3.14). 360 degrees is 2 x PI radians or around 6.28. We use radians to determine the diameter of the arc.
The arc takes five arguments. The first two arguments are the arc's X and Y center point. The third argument is the arc's radius. The last two arguments are starting and ending radians. A radian value of 0 starts at what would be the 3 o'clock position on a clock. If we want to draw a semi-circle, we give a starting radian value of 0 and an ending radian value of Math.PI. (Math is another object that has properties and methods—PI, around 3.14, is a property of the Math object.) To create a full circle, we set our last two arguments to 0 and 2 * Math.PI.
The final line of code in this section calls the fill() method which fills the arc shapes with the color of context's fillStyle property.
Type in the code, save your JavaScript file, and view your HTML file in a browser. You'll see three circles just below the three squares.
Now let's create three green triangles. Add these four lines of code:
context.lineWidth = 6;
context.lineJoin = 'round';
context.strokeStyle = '#000';
context.fillStyle = '#72bd1b';
We've set the values on four context properties: lineWidth is the width in pixels of stroke; lineJoin set to round, rounds the corners of our strokes; strokeStyle sets all outlines to the color black (#000 is a shorthand hexadecimal number—it's the equivalent of #000000); and fillStyle sets the fill of each subsequent shape to a green.
To create a triangle, we're going to create a path that's a series of points. Type in the following seven lines of code:
context.beginPath();
context.moveTo(490, 340);
context.lineTo(540, 440);
context.lineTo(440, 440);
context.closePath();
context.stroke();
context.fill();
beginPath() starts a new path. moveTo() is a context method that sets the starting point of a path—think of a path as drawing an outline and your starting point would be the place you first put your pen to paper. moveTo() takes two arguments: the position of X and Y.
The lineTo() method creates the next point on our path; it takes two arguments, X and Y position. We call lineTo() twice with different arguments, creating two new points on our path. Then we complete that path (join the last point to the starting point) with a closePath() method.
Finally we stroke and fill the triangle shape with the stroke() and fill() methods.
Now let's draw two more triangles. We'll pass different arguments to the moveTo() and lineTo() methods to shift each triangle's X position to the right.
context.beginPath();
context.moveTo(610, 340);
context.lineTo(660, 440);
context.lineTo(560, 440);
context.closePath();
context.stroke();
context.fill();
context.beginPath();
context.moveTo(730, 340);
context.lineTo(780, 440);
context.lineTo(680, 440);
context.closePath();
context.stroke();
context.fill();
The final code looks like this:
//Draw Shapes
//Draw squares, circles, and triangles
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//draw squares
//rect arguments: x, y, width, height
context.strokeStyle = '#158ad4';
context.rect(440, 40, 100, 100);
context.rect(560, 40, 100, 100);
context.rect(680, 40, 100, 100);
context.stroke();
//draw circles
//arc arguments: centerX, centerY, radius, start radian, end radian
context.fillStyle = '#e22011';
context.beginPath();
context.arc(490, 240, 50, 0, 2*Math.PI);
context.arc(610, 240, 50, 0, 2*Math.PI);
context.arc(730, 240, 50, 0, 2*Math.PI);
context.fill();
context.lineWidth = 6;
context.lineJoin = 'round';
context.strokeStyle = '#000';
context.fillStyle = '#72bd1b';
//draw triangles
//moveTo arguments: x, y position
//lineTo arguments: x, y position
context.beginPath();
context.moveTo(490, 340);
context.lineTo(540, 440);
context.lineTo(440, 440);
context.closePath();
context.stroke();
context.fill();
context.beginPath();
context.moveTo(610, 340);
context.lineTo(660, 440);
context.lineTo(560, 440);
context.closePath();
context.stroke();
context.fill();
context.beginPath();
context.moveTo(730, 340);
context.lineTo(780, 440);
context.lineTo(680, 440);
context.closePath();
context.stroke();
context.fill();
Save your JavaScript file and view your HTML file in a browser. You'll see three blue-outlined squares, three solid red circles, and three black-outlined, green triangles. You've created nine shapes using context's drawing methods.