HTML and CSS Reference
In-Depth Information
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Random 5</title>
<link rel="stylesheet" href="style.css">
</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;
while (numDots--) {
var x1 = Math.random() * canvas.width,
x2 = Math.random() * canvas.width,
x = (x1 + x2) / 2,
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 you generate two random numbers, x1 and x2 , and set the dot's x position to the average of them.
The y position is simply randomly near the center. This example gives you something like what you see in
Figure 19-7.
Figure 19-7. Biased distribution with one iteration
The effect isn't too pronounced here, but you can see that there is a bit more clumping in the center, and
more space at the edges. Creating more random numbers and averaging them makes it more obvious. We
can move this into a for loop to make it more versatile in the next example ( 08-random-6.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Random 6</title>
<link rel="stylesheet" href="style.css">
Search WWH ::




Custom Search