Reputation: 715
I'm currently trying to create a particle system for HTML5 canvas for a game, and I needed to make the particles fade out over time. I didn't want to have to be limited to rgba(), so I tried to use ctx.globalAlpha = alpha. The code to make it fade works, but I can not erase the last circles, they just fade out too, and it creates a line.
Here is the JS code:
class Particle{
//Non important declarations
display(ctx){
this.a = this.a < 0 ? 0 : this.a;
ctx.globalAlpha = 1;
ctx.globalAlpha = this.a;
ctx.fillStyle=this.color;
ctx.arc(this.x, this.y, this.rad, 0, Math.PI*2, false);
ctx.fill();
}
}
let P=new Particle(200, 200, 20, 180, 270, 5, 0.01, "blue");
const can= document.getElementById("canvas");
const c= can.getContext("2d");
can.height=innerHeight;
can.width=innerWidth;
clear=function(col){
c.globalAlpha=1;
c.fillStyle=col;
c.fillRect(0,0,innerWidth,innerHeight);
}
window.setInterval(function (){
clear("white");
P.update();
P.display(c);
Where did I mess up or need to add something?
Upvotes: 3
Views: 759
Reputation: 896
You need to wrap the code that draw the particle inside .save() and .restore()
ctx.save();
this.a = this.a < 0 ? 0 : this.a;
ctx.globalAlpha = this.a;
ctx.fillStyle=this.color;
ctx.arc(this.x, this.y, this.rad, 0, Math.PI*2, false);
ctx.fill();
ctx.restore();
This way the changes made to global properties (globalAlpha, fillStyle...) will not affect other particles.
I had not understood the problem. you are drawing one particle but because you do not call .beginPath() the calls to .arc() accumulate, and on every update all the previous arcs are redrawn
You must call .beginPath() before drawing each circle:
display(ctx){
ctx.save();
this.a = this.a < 0 ? 0 : this.a;
ctx.globalAlpha = this.a;
ctx.fillStyle=this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.rad, 0, Math.PI*2, false);
ctx.fill();
ctx.restore();
}
Note: you still need to use .save()/.restore() if you plan on adding more particles
Upvotes: 3