Particles with lifespan
by jonnyc
HTML
<html>
<head>
<title>Canvas</title>
<script type="text/javascript">
// When the window has loaded, DOM is ready. Run the draw() function.
</script>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>
CSS
#myCanvas{
background:black;
}
body{
overflow:hidden;
}
JavaScript
$(document).ready(function(){
// Create an array to store our particles
var particles = [];
// The amount of particles to render
var particleCount = 99;
// The maximum velocity in each direction
var maxVelocity = 3;
// The target frames per second (how often do we want to update / redraw the scene)
var targetFPS = 33;
// Set the dimensions of the canvas as variables so they can be used.
var canvasWidth;
var canvasHeight;
function updateBounds(){
canvasHeight = $(window).height();
canvasWidth = $(window).width();
$('#myCanvas').attr("height", $(window).height());
$('#myCanvas').attr("width", $(window).width());
}
$(window).resize(updateBounds);
updateBounds();
var arcOptim = 2 * Math.PI;
// Create an image object (only need one instance)
var imageObj = new Image();
// Once the image has been downloaded then set the image on all of the particles
imageObj.onload = function() {
particles.forEach(function(particle) {
particle.setImage(imageObj);
});
};
// Once the callback is arranged then set the source of the image
//imageObj.src = "http://www.blog.jonnycornwell.com/wp-content/uploads/2012/07/Smoke10.png";
// A function to create a particle object.
function Particle(context) {
// Set the initial x and y positions
this.x = 0;
this.y = 0;
// Set the initial velocity
this.xVelocity = 0;
this.yVelocity = 0;
// Set the radius
this.radius = 20;
// Store the context which will be used to draw the particle
this.context = context;
this.accel = 2;
// The function to draw the particle on the canvas.
this.draw = function() {
if(!this.isAlive){
return;
}
var multiplier = 1-(this.lifeRemaining / this.totalLife);
var size = this.radius * multiplier ;
var opac = 1-multiplier;
// If an image is set draw it
if(this.image){
var imageSize = 128;
...