Draw particles with differing settings by using a function
Since you're new to coding, I'm wondering if you know about functions
.
- A
function
is a reusable block of code.
- You can send
arguments
for a function to use.
- Arguments can make the function apply different setting while executing its code.
Here's a quick example using a single function
that accepts different arguments to draw your particles with different settings.
In general, you can apply different setting by creating a function that accepts parameters to draw the varied settings. That way you can call that same function multiple times with different setting.
// draw a small red circle at [x=50,y=50] with full alpha
drawParticle(50,50,10,'red',1.00);
// draw a large green circle at [x=150,y=100] with half alpha
drawParticle(150,100,50,'green',0.50);
function drawParticle(cx,cy,radius,color,alpha){
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2);
ctx.fillStyle=color;
ctx.globalAlpha=alpha;
ctx.fill();
}
For more complex settings you can use if
statements to draw the varied settings
For example, this function lets you draw a particle that "ages" from 0 to 100.
Pass in the particle's age as an argument and the function uses if
statements to reduce the particle's alpha as it ages.
function drawParticle(cx,cy,radius,color,age){
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2);
ctx.fillStyle=color;
if(age<25){
ctx.globalAlpha=1.00;
}else if(age<50){
ctx.globalAlpha=.75;
}else if(age<75){
ctx.globalAlpha=.50;
}else{
ctx.globalAlpha=.25;
}
ctx.fill();
}