JS exercise 4 – Random Lines

The topics of this exercise is intervals (triggering functions recurrently), and generating random values. In the exercise, lines are created from the center of the canvas to a random point, with a random shade of blue. Here is the full code:

<!DOCTYPE html>
<html>
<head>
	<title>Random lines</title>
	<script type="text/javascript">
	var cvs, ctx;
	function setup(){
		cvs=document.getElementById("myCanvas");
		ctx=cvs.getContext("2d");
		setInterval(draw,10);
	}
	function draw(){
		var cwidth = cvs.width;
		var cheight = cvs.height;
		var randomX = Math.random()*cwidth;
		var randomY = Math.random()*cheight;
		var randomB = Math.round(Math.random()*255);
		ctx.beginPath();
		ctx.strokeStyle="rgb(0,0,"+randomB+")";
		ctx.lineWidth=0.1;
		ctx.moveTo(cwidth/2,cheight/2);
		ctx.lineTo(randomX,randomY);
		ctx.stroke();
	}
	</script>
</head>
<body onload="setup()">
	<canvas id="myCanvas" width="400" height="400" style="border:1px solid">
	</canvas>
</body>
</html>

Inside the setup() function, we include the initial actions to be executed, similarly to Processing. The following line of code triggers the draw() function every 10 milliseconds:

setInterval(draw,10);

Because we’ve split up our code into two functions, we need to declare the variables that will be used by both at the beginning, outside of the functions:

var cvs, ctx;

The draw() function will take care of our repeating commands. Method Math.random() outputs a random (meaning “pseudo random”) floating point between 0 and 1. To obtain a random point in the x axis of the canvas, for example, we multiply this by the canvas width:

var randomX = Math.random()*cwidth;

To obtain a random blue value, we multiply by 255. However, the resulting number is a float, which in this case is a problem, since we need an integer as color value. So we should round it, using the Math.round() method:

var randomB = Math.round(Math.random()*255);

This is a screenshot of the resulting animation:

Link: http://mlab.taik.fi/mediacode/coursefiles/course_2011_10/4-random_lines.html

Advertisements

One thought on “JS exercise 4 – Random Lines

  1. Pingback: HTML5 Canvas Basics – Lines « 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