A more complex example
Functions
- Functions are just objectes, and can be declared a number of ways.
- I mostly stick with the C++ way.
- Parameters are a bit tricky, but we will put those off for a bit.
- I want to build a RandomPattern() function that I can call at the press of a button.
- This will clear the canvas
- Loop over a preset number of points
- Generate a random color
- Generate a random location.
- The fuction declaration
function RandomPattern() {
var i; // a loop control variable.
var x,y; // random coordinates.
var r,g,b; // random red, green and blue color components.
var color; // the color string
// function body
return;
}
Now the body
Generate the random colors and positions.
// generate a random color
r = Math.floor(Math.random()*255);
g = Math.floor(Math.random()*255);
b = Math.floor(Math.random()*255);
color = "rgb("+r+","+g+","+b+")";
CTX.fillStyle = color;
// and a random point.
x = Math.random()*WIDTH;
y = Math.random()*HEIGHT;
We will discuss colors later, but you probably know html colors have a red, green and blue component between 0 and 255.
Look here for a primer.
The rgb(r,g,b) html command generates a color
In javascript, Math.random() generates a random nuber between n, 0 ≤ n < 1
Math.floor(n) returns the integer less than or equal to n.
Oh, and I am doing string concatenation and conversion from int to string in the color= line
Finally draw the point
CTX.fillRect(x, y, 2, 2);
After the function is defined, I call it once, so it sets up the canvas on startup.
return;
}
RandomPattern();
One last bit, I want to be able to redraw the dots.
- I will do this with an <button> tag.
- A reference is here.
<button type="button" onclick="RandomPattern()">Redraw</button>
When the button is clicked, the function RandomPattern() is called.
The code and results