HTML and CSS Reference
In-Depth Information
dust is a million times heavier than a single water molecule, each collision doesn't do much. But when you
have so many millions of collisions per second, it starts to add up.
Some of the molecules might hit on one side, and some on the other. Overall, they are going to generally
average out. But over time, you see fluctuations. Where more molecules hit, say, on the left side, is
enough to start the particle moving a bit to the right. Then more might hit on the bottom, and the particle
moves upward. Again, these eventually average out, so it doesn't usually result in much momentum in any
one direction. You get this random floating-around motion.
We can easily simulate effect in an animation. On each frame, you calculate random numbers to add to
the x and y velocity of a moving object. The random numbers should be calculated to be either positive or
negative, and usually quite small, say in a range from -0.1 to +0.1. You can do that like so:
vx += Math.random() * 0.2 - 0.1;
vy += Math.random() * 0.2 - 0.1;
Multiplying the random decimal by 0.2 gives you a number from 0.0 to 0.2, and subtracting 0.1 makes it -
0.1 to 0.1. It's important to add some friction into this, otherwise the velocities will build up, and things zip
around unnaturally. In the example 01-brownian-1.html , we create 50 particles and have them floating
around with Brownian motion. The particles are instances of our familiar Ball class, made small and
colored black. Here is the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Brownian 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
dots = [],
numDots = 50,
friction = 0.95;
for (var dot, i = 0; i < numDots; i++) {
dot = new Ball(1, "#000000");
dot.x = Math.random() * canvas.width;
dot.y = Math.random() * canvas.height;
dot.vx = 0;
dot.vy = 0;
dots.push(dot);
}
function draw (dot) {
dot.vx += Math.random() * 0.2 - 0.1;
Search WWH ::




Custom Search