Particles with lifespan
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="100vw" height="100vh"></canvas>
</body>
</html>
CSS
#myCanvas{
background:black;
}
body{
overflow:hidden;
}
JavaScript
// Create an array to store our particles
var particles = [];
// The amount of particles to render
var particleCount = 360;
// The maximum velocity in each direction
var maxVelocity = 1.5;
// The target frames per second (how often do we want to update / redraw the scene)
var targetFPS = 60;
// 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;
// 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;
// The function to draw the particle on the canvas.
this.draw = function() {
if(!this.isAlive){
return;
}
var multiplier = (this.lifeRemaining / 100);
var size = this.radius * multiplier ;
// Draw the circle as before, with the addition of using the position and the radius from this object.
this.context.beginPath();
this.context.arc(this.x, this.y, size, 0, arcOptim, false);
this.context.fillStyle = this.color;
this.context.fill();
this.context.closePath();
};
// Update the particle.
this.update = function() {
--this.lifeRemaining;
if(this.lifeRemaining<=0){
this.isAlive = false;
}
if(!this.isAlive){
this.init();
return;
}
// Update the position of the particle with the...