Skip to content

Instantly share code, notes, and snippets.

@developit
Created July 1, 2015 17:47
Show Gist options
  • Save developit/55c04a1b84aae63ed5e5 to your computer and use it in GitHub Desktop.
Save developit/55c04a1b84aae63ed5e5 to your computer and use it in GitHub Desktop.
OVzLRK
// Set the dimensions of the canvas as variables so they can be used.
const WIDTH = 400;
const HEIGHT = 400;
// The amount of particles to render
const PARTICLE_COUNT = 50;
// The maximum velocity in each direction
const MAX_VELOCITY = 2;
// smoke particle image
const SMOKE = 'http://www.blog.jonnycornwell.com/wp-content/uploads/2012/07/Smoke10.png';
let particles = [];
let ctx;
let rnd = (min, max) => (Math.random() * (max - min) + min);
class Particle {
constructor(opts={}) {
this.x = this.y = 0;
this.randomize();
for (let i in opts) if (opts.hasOwnProperty(i)) {
this[i] = opts[i];
}
}
draw(ctx) {
if(!this.image) return;
ctx.drawImage(
this.image,
this.x - this.image.width/2,
this.y - this.image.height/2
);
}
update() {
let w = this.image && this.image.width || 0,
h = this.image && this.image.height || 0;
// Update the position of the particle with the addition of the velocity.
this.x += this.dx;
this.y += this.dy;
if ((this.x+w+10)<0) {
this.randomize();
this.dx = Math.abs(this.dx);
this.x = WIDTH;
}
else if ((this.x-10)>WIDTH) {
this.randomize();
this.dx = -Math.abs(this.dx);
this.x = -w;
}
if ((this.y+h+10)<0) {
this.randomize();
this.dy = -Math.abs(this.dy);
this.y = HEIGHT;
}
else if ((this.y-10)>HEIGHT) {
this.randomize();
this.dy = Math.abs(this.dy);
this.y = -h;
}
}
randomize() {
this.dx = rnd(-MAX_VELOCITY, MAX_VELOCITY)/2 || 1;
this.dy = rnd(-MAX_VELOCITY, 0) - 1;
}
}
function init() {
let canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
let image = new Image();
image.onload = λ => {
for (let i=PARTICLE_COUNT; i--; ) {
particles.push(
new Particle({
image,
x: rnd(0, WIDTH),
y: rnd(0, HEIGHT)
})
);
}
frame();
};
image.src = SMOKE;
}
function frame() {
ctx.fillStyle = "rgba(100,100,100,0.1)";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// Go through all of the particles and draw them.
for (let i=particles.length; i--; ) {
particles[i].update();
particles[i].draw(ctx);
}
requestAnimationFrame(frame);
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment