Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Created May 16, 2012 06:01
Show Gist options
  • Save gerardpaapu/2707908 to your computer and use it in GitHub Desktop.
Save gerardpaapu/2707908 to your computer and use it in GitHub Desktop.
html, body {}
<canvas id="myCanvas" width="400" height="400" />​
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var WIDTH = c.width, HEIGHT=c.height;
function init(){
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function Particle () {}
Particle.prototype.x = 0;
Particle.prototype.y = 0;
Particle.prototype.vx = 0;
Particle.prototype.vy = 0;
Particle.prototype.radius = 10;
Particle.prototype.color = "#0000FF";
Particle.prototype.currentTime = 0;
Particle.prototype.maxTime = 0;
Particle.prototype.alive = true;
Particle.prototype.setPosition = function (x, y) {
this.x = x;
this.y = y;
};
Particle.prototype.setVelocity = function (x, y) {
this.vx = x;
this.vy = y;
};
Particle.prototype.setAppearance = function (radius, color) {
this.radius = radius;
this.color = color;
};
Particle.prototype.setValues = function (x, y, vx, vy, radius, color, life) {
this.setPosition(x, y);
this.setVelocity(vx, vy)
this.setAppearance(radius, color);
this.maxTime = life;
};
Particle.prototype.draw = function() {
if (this.alive) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
};
Particle.prototype.update = function () {
if (this.alive) {
this.x = this.x + this.vx;
this.y = this.y + this.vy;
this.currentTime += 1;
// if time has run out for this particle
if (this.maxTime !== 0 &&
this.currentTime >= this.maxTime) {
this.alive = false;
}
// if this particle has gone out of bounds
if (this.x > WIDTH || this.x < 0 ||
this.y > HEIGHT || this.y < 0) {
this.alive = false;
}
}
this.draw();
};
Particle.makeRandom = function () {
function random(min, max) {
var range = max - min;
return (Math.random() * range) + min;
};
var particle = new Particle();
particle.setPosition(random(0, WIDTH), random(0, HEIGHT));
particle.setVelocity(random(-10, 10), random(-10, 10));
return particle;
};
var particles = [];
function initParticles() {
for (var i = 0; i < 10; i++) {
particles.push(Particle.makeRandom());
}
}
function updateParticles() {
clear();
for (var i = 0; i < particles.length; i++){
particles[i].update();
if (!particles[i].alive) {
// if the particle is dead, remove it and
// replace it with a new one
particles.splice(i, 1, Particle.makeRandom());
}
}
}
initParticles();
intervalId = setInterval(updateParticles, 1000 / 30);​
name: Particles
description: Some description, please keep it in one line
authors:
- Gerard Paapu
- isaac_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment