JS exercise 8 – Random Text

In this exercise, we will look into arrays, text display and keyboard input, and mix all of this into one exercise. The aim of the exercise is to juxtapose successive random quotes on the canvas.

This is the resulting code:

<!DOCTYPE html>
<html>
<head>
	<title>Random Text</title>
	<script type="text/javascript">
	var canvas, ctx;
	var quotes = new Array();
	//or you can also use:
	//var quotes = [];
	function setup(){
		//canvas and context setup
		canvas=document.getElementById("myCanvas");
		ctx=canvas.getContext("2d");
		//create values for the array
		quotes[0]="The Work of Art in the Age of Mechanical Reproduction";
		quotes[1]="Walter Benjamin";
		quotes[2]="In principle a work of art has always been reproducible";
		quotes[3]="The presence of the original is the prerequisite to the concept of authenticity";
		quotes[4]="The uniqueness of a work of art is inseparable from its being imbedded in the fabric of tradition";
		quotes[5]="Works of art are received and valued on different planes";
		//function calls
		setInterval(draw,100);
		window.addEventListener("keydown",checkKeyboard);
	}
	function draw(){
		var randomIndex = Math.floor(Math.random()*quotes.length);
		var randomColor = Math.round(Math.random()*255);
		var randomX = Math.random()*canvas.width*2-canvas.width/2;
		var randomY = Math.random()*canvas.height;
		var randomSize = Math.random()*90+10;
		ctx.fillStyle="rgba(0,"+randomColor+",0,0.5)";
		ctx.font=randomSize+"px Impact, Charcoal, sans-serif";
		ctx.fillText(quotes[randomIndex],randomX,randomY);
		ctx.strokeStyle="rgba(255,"+randomColor+",255,0.9)";
		ctx.lineWidth=3;
		ctx.strokeText(quotes[randomIndex],randomX,randomY);

	}
	function checkKeyboard(myEvt){
		if(myEvt.keyCode==67){
		ctx.clearRect(0,0,canvas.width,canvas.height);
		}
	}
	</script>
</head>
<body onload="setup()">
	<canvas id="myCanvas" width="400" height="400" style="border:1px solid"></canvas>
	<p>Press "C" to clear the canvas</p>
</body>
</html>

JavaScript arrays are “list-like objects that come with a several built-in methods to perform traversal and mutation operations. Neither the size of an array nor the types of its elements are fixed. ” (from Mozilla) More on arrays:

We initialize the array “quotes” at the start of the code:

var quotes = new Array();

Array elements have indexes, starting in 0. The index is encapsulated in square brackets. For example:

quotes[2]="In principle a work of art has always been reproducible";

We define a few such quotes in the setup() function. My quotes came from Walter Benjamin’s The Work of Art in the Age of Mechanical Reproduction.

Within the recurrent draw() function, a random quote is picked by calculating a random index, stored in a variable named (conveniently) “randomIndex”. To calculate this index, we need to obtain the maximum index. That is given to us by the property length of the array: quotes.length. The maximum index is equal to length minus 1, as the first index is 0. We multiplied Math.random() by quotes.length, obtaining a number between 0 and quotes.length. By applying the Math.floor rounding method, which rounds a floating point number to its preceding integer, we achieve the desired result: an interval between 0 and quotes.length -1:

var randomIndex = Math.floor(Math.random()*quotes.length);

We then calculate a random color and position (variables randomColor, randomX, randomY), using methods we have used several times in previous exercises. We also calculate a randomSize variable for the text (in pixels), in this case between 10 and 100:

var randomSize = Math.random()*90+10;

The font style is defined by the following function, in which our random size and the “Impact, Charcoal, sans-serif” font family is applied:

ctx.font=randomSize+"px Impact, Charcoal, sans-serif";

More on font families:

And further explorations regarding fonts:

The text is rendered in the canvas using the following code, which applies the fillStyle we had defined previously:

ctx.fillText(quotes[randomIndex],randomX,randomY);

The first parameter of fillTextis the text itself to be displayed, in this case using an array and a random index. The next two parameters are x and y coordinates.

We also define a different strokeStyle, and a stroke for the text:

ctx.strokeText(quotes[randomIndex],randomX,randomY);

Finally, we create a functionality to clear the canvas when the “c” key in the keyboard is pressed. First, we create a listener that checks for key presses, and triggers a “checkKeyboard” function when a key press occurs. The listener is associated to the window DOM object (check my DOM post), since a key press is not constrained to the canvas as a mouse event is:

window.addEventListener("keydown",checkKeyboard);

The event that is checked is “keydown”. For a list of DOM events, please check this link.

If the code of the key pressed matches the key code of “c” (67), then the canvas is cleared using the clearRect method:

if(myEvt.keyCode==67){
	ctx.clearRect(0,0,canvas.width,canvas.height);
}

The key code of the key pressed is passed to the function by the event listener via a parameter that we entitled “myEvt” (checkKeyboard(myEvt)). The parameters of clearRect are: x, y, with, height.

A list of key codes can be found here. Additionally, W3C has a page where you can obtain a key code by pressing the respective key.

One nice, simple example – moving a circle with key presses:

http://html5.litten.com/moving-shapes-on-the-html5-canvas-with-the-keyboard/

This is a screenshot of the resulting applet:

Link to the exercise: http://mlab.taik.fi/mediacode/coursefiles/course_2011_10/8-random_text_arrays.html

Advertisements

1 thought on “JS exercise 8 – Random Text

  1. Pingback: HTML5 Canvas – Arrays and Random text (Photowash edit) « Valeria's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s