HTML and CSS Reference
In-Depth Information
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
numDots = 300,
iterations = 6;
while (numDots--) {
for (var i = 0, xpos = 0; i < iterations; i++) {
xpos += Math.random() * canvas.width;
}
var x = xpos / iterations,
y = canvas.height / 2 + Math.random() * 50 - 25;
context.fillStyle = "#000000";
context.beginPath();
context.arc(x, y, 2, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
}
};
</script>
</body>
</html>
Here the iterations variable controls how many numbers you will average. You start with the variable
xpos equal to zero, and add each random number to it. Finally, you divide that total by the number of
iterations for the final value. Figure 19-8 shows the results.
Figure 19-8. Biased distribution with six iterations
It is now easy to do the same thing for the y-axis, and example 09-random-7.html does just that:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Random 7</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
Search WWH ::




Custom Search