HTML and CSS Reference
In-Depth Information
You can swap out the gravity code and plug the spring code into the previous examples, but the effect might not
be interesting. The particles would eventually just lump into a mass—springs can't tolerate distance.
So here's the dilemma: You want particles to attract with a spring force, but you want them to tolerate
some distance and not pull themselves together. We solve this by setting a minimum distance for the
particles to be within before they react to one another. If the particles are farther apart than this, they
ignore each other.
A springy node garden
Let's make our own springy node garden example that we go through step by step. Here is the code listed
in its entirety (document 06-node-garden.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Node Garden</title>
<link rel="stylesheet" href="style.css">
<style>
#canvas {
background-color: #000000;
}
</style>
</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,
minDist = 100,
springAmount = 0.001;
for (var particle, i = 0; i < numParticles; i++) {
particle = new Ball(5, "#ffffff");
particle.x = Math.random() * canvas.width;
particle.y = Math.random() * canvas.height;
particle.vx = Math.random() * 6 - 3;
particle.vy = Math.random() * 6 - 3;
particles.push(particle);
}
function spring (partA, partB) {
var dx = partB.x - partA.x,
dy = partB.y - partA.y,
dist = Math.sqrt(dx * dx + dy * dy);
 
Search WWH ::




Custom Search