![Javascript](assets/m13_sidebar.jpg)
Interactive Canvas Tag and jQuery UI
In our previous module, we began exploring the canvas tag. It gave us a chance to explore Javascript and have some fun creating graphics dynamically using the drawing API. We used the for loop to automate our script.
In this module, we are going to take our exploration further. We are going to use the canvas tag to create a drawing application. Using the canvas tag, we will write code that will allow our users to draw into the browser window.
To improve the experience, we will use the jQuery UI library. We will use sliders to control the width and opacity of the stroke. And then we can get fancy and use sliders to create a simpler color mixer.
But before we can move forward, we will need to cover one more important Javascript concept: arrays.
Making Lists: Arrays
Arrays are variables. A simple variable can only hold one value. An array, on the other hand, can hold as many values as needed. In essence, arrays are lists. They can be organized and manipulated as a unit, or opened up and examined piece by piece. Like all variables, arrays are containers -- they contain something of value. Unlike other variables, arrays can be structured to keep our valuables neat and organized.
Arrays can hold all kinds of values, numbers, strings and objects -- even other arrays. They can be likened to a fishing tackle box with a place for everything and everything in its place. Each of the little compartments can be numbered or named for easy retrieval.
You declare an array like this:
var dogTypes = new Array();
That is the formal declaration. You could use the shortcut with square braces used by most developers:var dogTypes = [];
Like any other variable, arrays can hold any legal data type. Since arrays are lists, you can list the items in your array and separate the items with commas. Your array can hold as many items as you like.Here is the array populated with data:
var dogTypes = [
"greyhound",
"labrador retriever",
"Australian cattle dog",
"kosher hot dog"
];
In this example, the data is all in the form of strings, but it could have been numbers, expressions, objects, etc.
The array provides the structure for the content. An array can be thought of as a chest of drawers. A dresser might have four drawers: the top one might have socks, the second has T-shirts, the third, pants, and the fourth, pajamas. When we refer to the array, we are referring to the dresser that holds the content, not the content itself.
A drawer in an array can be called an "element" or "index" and is, by default, numbered. Arrays use a zero-based counting system. The first element in an array is in the zero position. The second element is in the one position, and so on.
Unlike a chest of drawers, arrays can hold an unlimited number of elements, and the number can change at any moment. Extra drawers can be added as needed and old ones removed. The drawers can be emptied or filled at will.