HTML and CSS Reference
In-Depth Information
itself and handling any reactions. Either way works, but for the examples in this topic, the animation code
is kept outside of the particle object for simplicity's sake.
The general setup for the code is the same in each of the examples here, because most of the variations
are in the interaction and attraction between the particles. Here's the basic document that we build on,
which creates several particles and positions them randomly around the canvas element:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Particles</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'),
particles = [],
numParticles = 30;
for (var particle, i = 0; i < numParticles; i++) {
particle = new Ball(5);
particle.x = Math.random() * canvas.width;
particle.y = Math.random() * canvas.height;
particle.mass = 1;
particles.push(particle);
}
function draw (particle) {
particle.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(draw);
}());
};
</script>
</body>
</html>
Here, you create 30 particles and initialize each one's radius to 5 and set the mass to 1. Later on, we'll
change that around to get different effects. You can also start off the particles with a random velocity or
randomly size them.
Search WWH ::




Custom Search