HTML and CSS Reference
In-Depth Information
Figure 19-4. This method starts to form a square. Not so random looking anymore.
As you see, the dots are starting to form a square. Maybe that's what you want, but if you try to make
something like an explosion or star system, a square doesn't look too natural. So let's move on to the next
technique.
Circular distribution
Although slightly more complex than a square distribution, circular distribution really isn't very difficult to
do. First you need to know the radius of your circle. Let's keep it at 50, to match the last example. This is
the maximum radius that a dot can be placed from the center. For each dot, you take a random number
from zero to that number to use as the radius. Then you choose a random angle from 0 to PI * 2 radians
(360 degrees), and use a little trigonometry to find an x and y position to place the dot. Here's the code for
this example, 05-random-3.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Random 3</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,
maxRadius = 50;
while (numDots--) {
var radius = Math.random() * maxRadius,
angle = Math.random() * (Math.PI * 2),
x = canvas.width / 2 + Math.cos(angle) * radius,
y = canvas.height / 2 + Math.sin(angle) * radius;
 
Search WWH ::




Custom Search