Arrays

Download the scripts for this exercise about Arrays

Arrays let us store groups of data. They house groups of variables, numbers, strings, objects, and even other arrays.

You'll need a contemporary browser with javascript turned on to be able to see this page

When you create interactive projects, you’ll use arrays to store all kinds of data. They help you collect and organize your project data. You can also quickly access that data using for loops.

As a way to introduce arrays, let's draw three circles, centered on the screen. Each circle pulls its color from an array that holds three hexadecimal color values.

Create an HTML Page

Like before, create a basic HTML page, link the main.css file, and add a canvas tag and two script tags. Our first script tag brings in the responsive-canvas.js file and our second tag references the JavaScript file we’re about to create, color-arrays.js.

Create a JavaScript File

Create your JavaScript in Dreamweaver (File>New, choose JavaScript from the Document Type and press Create.) We’ll wrap our code in a self-executing anonymous function just as we did in our last exercise. And, as usual, we write the code that creates our canvas and context.

(function () {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),

})();

Now let’s add four variables that help us define the circles we plan to draw.

(function () {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
radius= 100,
xGap = 20,
x = (canvas.width - ((radius * 2 * 3) + (xGap * 2)))/2 + radius,
y = 300,

})();

Our circles will be the same size, each with a radius of 100 pixels. We’ll put a small gap of 20 pixels between each circle. We store the pixel amount in our variable xGap. All circles have the same Y position, 300 pixels from the top of the canvas. And our x variable calculates the position for the first circle so that all three circles are centered on our canvas. Each subsequent circle is placed 20 pixels (our xGap amount) from its neighbor circle.

(If you want more details on how we’re calculating that X position for our first circle, this is how it goes. We plan to draw three circles, each with a diameter of 200 (radius * 2) and a gap of 20 pixels (xGap) between the first, second, and third circles. We use the circle's diameters and gaps to determine the total space the circles occupy on screen (a width of 640 pixels—three diameters of 200 and two gaps of 20). Then we subtract that width from the canvas width (1200 - 640 = 560) and divide the leftover space by two (final number is 280). That number becomes the x position of our first circle's left edge. Finally we add in an extra radius because when arc() draws a circle, it draws from the circle’s center point not its top-left edge. Our final number for the starting x is 380 (280 + 100).)

Next we’ll create an array of colors:

circleColors = ['#72bd1b', '#f1ca13', '#ec9314'],

We’re creating an array and defining its values in one line of code. We set the variable circleColor equal to three hexadecimal colors surrounded by square brackets. Those square brackets tell the browser that we’re creating an array. Notice that each hexadecimal color is surrounded by quotes, a color format that context’s fillStyle accepts. Remember that fillStyle determines the color of the shapes you draw.

To complete the set-up of our script, create a ResponsiveCanvas object and its method, resizeCanvas().

(function () {
	var canvas = document.getElementById('myCanvas'),
	context = canvas.getContext('2d'),
	radius= 100,
	xGap = 20,
	x = (canvas.width - ((radius * 2 * 3) + (xGap * 2)))/2 + radius,
	y = 300,
	circleColors = ['#72bd1b', '#f1ca13', '#ec9314'],
	//Make your canvas responsive to the browser's window size
	myRC = new ResponsiveCanvas({canvasId:'myCanvas', divId:'interaction'});
	//resize your canvas
	myRC.resizeCanvas();

})();

Draw the Circles

Next we’ll create a function that’ll draw our three circles and give each one a color pulled from our circleColors array. We’ll do this with a for loop. Arrays and for loops are closely connected; you’ll often run through the data in an array using the capabilities of a for loop.

First, create a function below the script’s set-up code but above the right-facing curly bracket that closes our anonymous function:

function drawCircles() {
	
		
}

An Array’s Index

Before we write our for loop, let’s talk a little about arrays. We know now that arrays store a list of items, but how do you access an item in our list?

One way to retrieve an item is through an index which points to a particular item in an array, much like an index in a book points to a particular page in a book.

An array’s index is just a number, often a variable that we’ve defined. To retrieve the first item in an array, you set your index to zero. (You might think an index of one would pull the first item, but arrays are zero-based—their indices start at zero and count up.)

If we wanted to see the first item in our array, we could print the value to our Console panel like this:

console.log(circleColors[0]);

This would print to the Console the first item in our array: '#72bd1b'.

Notice the syntax: we type the array name and enclose the index in square brackets.

If we wanted to see the value of the third item in the array, we’d type this:

console.log(circleColors[2]);

drawCircles()

Back to our drawCircles() function. Let's set up our for loop so it loops through our array.

for (var i=0; i<circleColors.length; i++) {	

}

Remember that for loops have three statements. Our first statement initializes a counter to zero (var i=0;). Our next statement— a conditional statement—checks if the counter is less than our array’s length property (i<circleColors.length;). All arrays have length properties that store the total number of items in an array. Our circleColors array has three hexadecimal colors, so its length is equal to 3. Our last for-loop statement increments the counter by one at end of each loop (i++).

Next, inside the for loop’s curly brackets, we’ll add code to draw our circles.

for (var i=0; i<circleColors.length; i++) { context.fillStyle = circleColors[i];
  context.beginPath();
  context.arc(x, y, radius, 0, Math.PI * 2);
  context.fill();
  x += radius * 2 + xGap;}

Most of this should look pretty familiar. We’re setting the context’s fillStyle which determines the color of the shapes we draw to the canvas. Then we start a path, draw a circle, and fill it with color. One new thing is that we’re setting fillStyle with a color pulled from our circleColors array and the index we’re using is the for-loop’s counter.

The first time we run through this code, our counter is zero and our color is the first item in our array. In the second loop, our counter is one and we set fillStyle to the second hexadecimal color in our array. The third and last time through the loop, we set fillStyle to the last item in our array.

One more thing to note, we’re doing a quick calculation after we draw each circle. We’re taking our x variable and adding a circle’s diameter to it (radius * 2) and xGap, the gap between circles. This x variable is used when we call context’s arc() method; it’s passed as the circle’s center x point. Since we’re adding to x with each loop, each new circle is moved over to the right, creating a row of circles. Finally, notice that we have a plus sign before our equal sign—+= means add the value on the right to the current value of the variable on the left. We're increasing variable x's value by the circle's diameter plus xGap each time we run through the for loop.

We have one last thing to do to complete this script, we need to call the drawCircle’s function.

Add this line after the drawCircles() function:

drawCircles();

The complete code looks like this:

//Color Array
//Use an aray to store a list of colors and then apply those colors to circle shapes
(function () {
	var canvas = document.getElementById('myCanvas'),
	context = canvas.getContext('2d'),
	radius= 100,
	xGap = 20,
	x = (canvas.width - ((radius * 2 * 3) + (xGap * 2)))/2 + radius,
	y = 300,
	circleColors = ['#72bd1b', '#f1ca13', '#ec9314'],
	//Make your canvas responsive to the browser's window size
	myRC = new ResponsiveCanvas({canvasId:'myCanvas', divId:'interaction'});
	//resize your canvas
	myRC.resizeCanvas(); 

	function drawCircles() {
	
		for (var i=0; i<circleColors.length; i++) {	
			context.fillStyle = circleColors[i];
			context.beginPath();
			context.arc(x, y, radius, 0, Math.PI * 2);
			context.fill();
			x += radius * 2 + xGap;
		}
	
	}
	
	drawCircles();
})();

Save your JavaScript file and open your HTML page in a browser, you’ll see three circles in row, each with a different color, centered on the canvas.

An Array that Stores Objects

Let’s try something a little more complex. We just created an array that stored three hexadecimal colors. A circle’s color could be considered one of its defining characteristics. Circles have other characteristics too—a radius and X and Y center points. What if we bundled all those characteristics into a single object and used that object to draw a circle. We could make several objects each with different characteristics, store each object in an array, and then cycle through that array to draw different kinds of circles.

You'll need a contemporary browser with javascript turned on to be able to see this page

Let’s try it out.

Set Up Your Script

Create a new JavaScript file. I named my file, properties-array.js. Wrap the script inside a self-executing anonymous function and create the canvas and context.

function () {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),

})();

Next, let’s define our objects. We’re creating object literals—nameless objects that assign literal values—values like numbers or letters—to property names. Each object literal starts with a left-facing curly bracket and ends with a right-facing curly bracket. Inside those brackets we have name-value pairs—a property name followed by a colon and a value followed by a comma.

We’ll create three object literals that’ll define the characteristics of three circles. Add the object-literal code right after the canvas-and-context code:

(function () {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
circle1 = {x: 240, y:100, radius:30, color:'#72bd1b'},
circle2 = {x: 500, y: 360, radius: 120, color: '#f1ca13'},
circle3 = {x: 860, y: 200, radius: 80, color: '#ec9314'},


})();

Take a look at the first object literal:

(circle1 = {x: 240, y:100, radius:30, color:'#72bd1b'},

We’ve defined four properties: x, y, radius, and color. And we’ve assigned a value to each property (x is 240, y is 100, radius is 30, and color is '#72bd1b').

Next we’ll store each object literal in an array. Add this line of code:

circles = [circle1, circle2, circle3],

Then we’ll create our ResponsiveCanvas object and call its resizeCanvas() method. Here’s our set-up-the-script code:

(function () {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
circle1 = {x: 240, y:100, radius:30, color:'#72bd1b'},
circle2 = {x: 500, y: 360, radius: 120, color: '#f1ca13'},
circle3 = {x: 860, y: 200, radius: 80, color: '#ec9314'},

circles = [circle1, circle2, circle3],
myRC = new ResponsiveCanvas({canvasId:'myCanvas', divId:'interaction'});
myRC.resizeCanvas();

})();

Now we’ll create a new drawCircles() function. We’ll use a for loop like before, cycling through our circles array, and create three circles that are defined by the object literals inside our array.

The code looks like this:

function drawCircles() {
	for (var i=0; i<circles.length; i++) {	
		context.fillStyle = circles[i].color;
		context.beginPath();
		context.arc(circles[i].x, circles[i].y, circles[i].radius, 0, Math.PI * 2);
		context.fill();	
	}
	
}

We set the for loops counter to zero (var i=0;), set up a conditional statement that checks if our counter is less than circle array’s length (i<circles.length;), and increment the counter by one at the end of each loop (i++).

Inside our for loop, we run four lines of code. We set the fillStyle to a color, begin a path, draw a circle, and fill that circle with a color. The difference this time, though, is we’re getting the values to draw our circle all from the array’s object literals

The first time through the loop, our counter is zero. That counter doubles as the index for our circles array. Look at the first line of code:

context.fillStyle = circles[i].color;

We’re setting the context’s fillStyle to the value of the first object literals color property which is a hexadecimal value of '#72bd1b'. Notice the syntax. We follow the array and its index (circles[i]) with a period and then add on the color property (circles[i].color). The index points to the first object literal in the array and color becomes a key that give us the object literal’s color value.

Look at the third line of code.

context.arc(circles[i].x, circles[i].y, circles[i].radius, 0, Math.PI * 2);

Now most of the arguments we send to context’s arc() method come from our object literal, stored in the circles array. Look at the first argument:

circles[i].x

We’re sending arc() the value of x which is defined in our object literal and stored in our circle array. We point first to the object (circles[i]) and then reference the object’s property x, and retrieve the value of x.

We do the same thing for y and radius.

Using object literals to bundle data together provides a way to quickly define lots of different shapes. Storing those object literals in an array means we can easily loop through that array, drawing lots of different shapes

One last thing to do. We need to call the drawCircle() function. Add this line after the drawCircles() function:

drawCircles();

Here's the complete code listing:

//Properties Array 
//Use an array to store a list of object literals that
//contain the properties and values of circle shapes 
(function () {
  var canvas = document.getElementById('myCanvas'),
  context = canvas.getContext('2d'),
  //create three objects with properties of x, y, radius, and color
  circle1 = {x: 240, y:100, radius:30, color:'#72bd1b'},
  circle2 = {x: 500, y: 360, radius: 120, color: '#f1ca13'},
  circle3 = {x: 860, y: 200, radius: 80, color: '#ec9314'},
  //store the three objects in an array
  circles = [circle1, circle2, circle3],
  //Make your canvas responsive to the browser's window size
  myRC = new ResponsiveCanvas({canvasId:'myCanvas', divId:'interaction'});
  //resize your canvas
  myRC.resizeCanvas(); 

  function drawCircles() {
	for (var i=0; i<circles.length; i++) {	
	  context.fillStyle = circles[i].color;
	  context.beginPath();
	  context.arc(circles[i].x, circles[i].y, circles[i].radius, 0, Math.PI * 2);
	  context.fill();	
	}
  }
  
  drawCircles();

})();

Save your JavaScript file. Create a new HTML file (or modify your previous HTML file), adding a script tag that points to our latest script. Open the HTML file in a browser and you’ll see three circles with different colors, sizes, and positions.

Download the code for this exercise on Arrays.