GRAPHIC JAVASCRIPT

Back to index

The Graphic JavaScript units will focus on creating simple graphical designs on the HTML5 Canvas utilizing scripts written in JavaScript. This is an introductory level course which will keep things simple, but which will provide students with a basic understanding of how to use JavaScript to create graphical designs on web pages.

BASIC TOOLS:

1. HTML5 Canvas
The following code shows how to place a canvas element on a web page.

<canvas id="myCanvas" width="400" height="100"> Optional message goes here</canvas>
JavaScript can be used to make something happen inside the canvas. Here is a very simple example of a few lines which produce a word which appears on the canvas area.
<script> var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); ctx.fillStyle="#aaaaff"; ctx.fillRect(0,0,400,100); ctx.font="80ps Arial"; ctx.fillStyle="#000000"; ctx.fillText("Hello!", 40, 80); </script>
Here's what this code produces:
Your browser does not support the HTML5 canvas tag.
Obviously, if all you wanted to do was to write "Hello!" on a blue background, there are simpler ways of doing it, but keep in mind that this is an introductory lesson and what we produce may be less than spectacular. The point, however, is to learn the basics, which will allow us to build up to creating more interesting projects.

The Example: As you can see there are seven lines between the SCRIPT tags (not couting the empty lines). Here's a basic line-by-line analysis of the example:
Line Number(s)Explanation
1 The variable can stores a reference to the canvas object previously defined on the page.
2 The variable ctx stores a reference to the context.
3 The fillStyle attribute is set to a shade of blue.
4 Using the fillRect(x,y,width,height) method the entire canvas area is painted with the current color.
5 The font attribute is set to a specific size and font type.
6 The fillStyle attribute is set to black.
7 The fillText(str,x,y) method is used to render a string within the canvas area.


ASSIGNMENT:

Create a new web page and on it display a modified version of the JavaScript applet shown on this page. Change the background color to yellow. Change the font color to red. Change to a slightly smaller font size and display two lines, both centered in the canvas area. The top line should say, "Hello, my name is" and the bottom line should be your first and last name.