Skip to content

Instantly share code, notes, and snippets.

@chabb
Created March 21, 2018 17:01
Show Gist options
  • Select an option

  • Save chabb/9f5be1533e61cb5428938e0c5aa76ce8 to your computer and use it in GitHub Desktop.

Select an option

Save chabb/9f5be1533e61cb5428938e0c5aa76ce8 to your computer and use it in GitHub Desktop.
Simple particle system
<canvas id="canvas" width="600px" height="400px"></canvas>
<script src="./index.js"></script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let shapes = 200;
let w = new Array(shapes);
let h = new Array(shapes);
let x = new Array(shapes);
let y = new Array(shapes);
let speedX = new Array(shapes);
let speedY = new Array(shapes);
let gravity = new Array(shapes);
let damping = new Array(shapes);
let friction = new Array(shapes);
let shapeCount = 0;
let birthRate = .25;
let sprayWidth = 5;
let width = 600;
let height = 400;
let bg = [50, 50, 50];
function setup() {
for (let i = 0; i < shapes; i++) {
x[i] = width / 2.0;
y[i] = 50;
w[i] = 2 + Math.floor(Math.random() * 17);
h[i] = w[i];
speedX[i] = -sprayWidth + Math.random() * (sprayWidth * 2);
speedY[i] = 0;
gravity[i] = .1;
damping[i] = .7 + Math.random() * ( .98 - .7);
friction[i] = .65 + Math.random() * (.95 - .65);
}
window.requestAnimationFrame(draw);
}
function draw() {
fill(bg, 0.062)
ctx.strokeStyle = 'black';
ctx.fillStyle = 'green';
for (let i = 0; i < shapeCount; i++) {
let color = `hsla(${80 + 58 * (y[i] / height)}, ${100}%, ${50 + 10 * (x[i] / width)}%, ${0.9})`;
ctx.fillStyle = color;
ctx.fillRect(x[i], y[i], w[i], h[i]);
x[i] += speedX[i];
speedY[i] += gravity[i];
y[i] += speedY[i];
// collision
if (x[i] >= width - w[i]) {
x[i] = width - w[i];
speedX[i] *= -1;
} else if (x[i] <= 0) {
x[i] = 0;
speedX[i] *= -1;
} else if (y[i] > height - h[i]) {
y[i] = height - h[i];
speedY[i] *= -1;
speedY[i] *= damping[i];
speedX[i] *= friction[i];
}
}
if (shapeCount < shapes) {
shapeCount += birthRate;
}
window.requestAnimationFrame(draw);
}
setup();
// fill entire canvas with a preset color
function fill(rgb, amt) {
ctx.beginPath(); // start path
ctx.rect(0, 0, width, height) // set rectangle to be the same size as the window
ctx.fillStyle = `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${amt})` // use the rgb array/color for fill, and amt for opacity
//ctx.fillStyle = 'black'
ctx.fill() // do the drawing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment