Reputation: 325
Since I added o: Math.random()*(1 - 0.1) + 0.1 //opacity
for charge random opacity values the animation doesn't work fluently. What can I do to prevent this? How do i make my script more effeciently regarding to the performance?
window.onload = function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = canvas.width = window.innerWidth;
var H = 550;
var mp = 45; //max particles
var particles = [];
//var rotate = 180;
reqAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
for ( var i = 0; i < mp; i++ )
{
particles.push({
x: Math.floor(Math.random()*W), //x-coordinate
y: Math.floor(Math.random()*H), //y-coordinate
d: Math.floor(Math.random()*(12 - 1) + 1), //density
r: Math.floor(Math.random()*(70 - 10) + 10), //radius
o: Math.random()*(1 - 0.1) + 0.1 //opacity
})
}
function animate() {
reqAnimFrame(animate);
for ( var i = 0; i < mp; i++ )
{
var p = particles[i];
p.x += p.d;
if(p.x >= W + p.r){
p.x = -300;
p.y = Math.floor(Math.random()*H);
}
draw();
}
}
function draw() {
ctx.clearRect(0, 0, W, H);
for ( var i = 0; i < mp; i++ )
{
var p = particles[i];
ctx.fillStyle = "rgba(51,51,51," + p.o + ")";
ctx.beginPath();
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, false);
ctx.fill();
//ctx.moveTo(p.x,p.y);
//ctx.lineTo(p.x + 150, p.y + (-180));
//ctx.lineTo(p.x + 300, p.y);
}
}
animate();
};//onload function
Upvotes: 0
Views: 213
Reputation: 11245
I make the jsfiddles one
and two
.
In first fiddle there is no closePath
function calling, in second fiddle it calling.
In first fiddle devtools timeline show extra memory usage 7 MB per second (after 1s calling CG in your case, IMHO): from 10 MB to 17 MB
In second fiddle timeline show extra memory usage 2 MB from beginPath
to closePath
functions (near 130ms): from 10 MB to 12 MB. But in this case CG don't call.
I think it will be better to add closePath
function, to prevent GC calling. And use less number of particles for old browsers, because as for me (MacBook Pro, Chrome) all works fine and fps was 60(maximum).
Upvotes: 2
Reputation: 19294
you are calling draw within your update loop once for each particle, which leads to a mp*mp cost instead of a mp cost.
First thing to do is to call draw only once per particle, so do not call it within your update loop, but just once at the end of the update.
Notice you can gain some performances by changing the context's globalAlpha instead of creating a new color.
Upvotes: 1