Create a Fire Particles Effect with Canvas, HTML 5 and Javascript
Realistic fire Particles Effect with
Canvas, HTML 5 and Javascript.
HTML
<div id="wrapper">
<canvas id="canvas"></canvas>
<img style="display:block;" id="background" src="https://s13.postimg.org/jyzmkb4nr/image.jpg" />
</div>
CSS
body {
background: black;
}
#wrapper {
width: 600px;
position: relative;
}
canvas {
display: block;
position: absolute;
top: -61px;
left: 279px;
}
#background {
width: 650px;
height: auto;
}
JavaScript
var c = document.getElementById('canvas'),
ctx = c.getContext('2d'),
cw = c.width = 1,
ch = c.height = 66,
parts = [],
partCount = 90,
partsFull = false,
rand = function(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min);
};
var FireParticle = function() {
this.reset();
};
FireParticle.prototype.reset = function() {
this.startRadius = this.radius = rand(1, 4);
this.x = cw / 2 + (rand(0, 6) - 3);
this.y = 250;
this.vx = this.vy = 0;
this.hue = rand(0, 65);
this.saturation = rand(60, 100);
this.lightness = rand(25, 75);
this.startAlpha = rand(3, 10) / 100;
this.alpha = this.startAlpha;
this.decayRate = .16;
this.startLife = this.life = 7;
this.lineWidth = rand(1, 15);
}
FireParticle.prototype.update = function() {
this.vx += (rand(0, 200) - 100) / 1500;
this.vy -= this.life / 50;
this.x += this.vx;
this.y += this.vy;
this.alpha = this.startAlpha * (this.life / this.startLife);
this.radius = this.startRadius * (this.life / this.startLife);
this.life -= this.decayRate;
if (
this.x > cw + this.radius ||
this.x < -this.radius ||
this.y > ch + this.radius ||
this.y < -this.radius ||
this.life <= this.decayRate
) {
this.reset();
}
};
FireParticle.prototype.render = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = ctx.strokeStyle = 'hsla(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness + '%, ' + this.alpha + ')';
ctx.lineWidth = this.lineWidth;
ctx.fill();
ctx.stroke();
};
var createParts = function() {
if (!partsFull) {
if (parts.length > partCount) {
partsFull = true;
} else {
parts.push(new FireParticle());
}
}
};
var updateParts = function() {
var i = parts.length;
while (i--) {
parts[i].update();
}
};
var renderParts = function() {
var i = parts.length;
while (i--) {
parts[i].render();
}
};
var clear = function() {
...