112 Chapter 5—Canvas
<script>
var canvas = document.querySelector("canvas");
var context = canvas.getContext('2d');
var drawBars = function(bars) {
context.clearRect(0,0,canvas.width,canvas.height);
for (var i=0; i<bars; i++) {
var yOff = i*(canvas.height/bars);
var w = Math.random()*canvas.width;
var h = canvas.height/bars*0.8;
context.fillRect(0,yOff,w,h);
context.strokeRect(0,yOff,w,h);
}
};
drawBars(10);
</script>
Calling this function with drawBars(10) deletes any existing content with clear-
Rect() and then draws the ten filled rectangle outlines in the for loop with fill-
Rect() and strokeRect(). The width w of the bars varies between 0 pixels and the
full width of the canvas element, and is determined randomly via the JavaScript
function Math.random(). The function Math.random() generates a number be-
tween 0.0 and 1.0, and is therefore ideal for producing random values for width,
height, and the position, depending on the canvas dimension. Multiplying with
the corresponding attribute value does the job.
The equally spaced, horizontal arrangement of the bars follows the canvas height.
The spaces between the bars result from multiplying the calculated maximal bar
height h by the factor 0.8.
The canvas width and height can be easily seen in the attributes canvas.width
and canvas.height as mentioned in the first example. Just as easily, we can ac-
cess the HTMLCanvasElement from the drawing context via its attribute context.
canvas and use it to generate new bars with each click on the canvas. Three lines
of code added after the drawBars(10) call are enough:
context.canvas.onclick = function() {
drawBars(10);
};
We have clarified how the ten bars are drawn, but how do we make them light
gray with black outlines? We will find the answer by looking at the options of as-
signing color in Canvas.