Hello I'm new to programming and I made a simple JavaScript that draws simple canvas.arc circles that moves in 2D x,y-coordinates.
and just out of curiosity I ran the animation with 1 particle 10, 100, 1000 and so on and on increasing the number of the particles.
What I observed was particles moving smoothly up to few hundreds but then it becomes very laggy* (sorry I don't know the right term for this phenomenon)
and I was thinking, how can my computer run games and software that are far more complicated so smoothly yet struggles to run simple script I made with difficulty?
I'd like to know the reason behind this or theory behind it!
ps sorry I'm not confident with my English anyway please do post sources or other links that may help me understand this question.
This is the code. Its very simple but if there is way to improve performance please do tell me id like to know for future scripting.
Try increasing the particle count:
var particleCount = 10000;
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
function(callback){
window.setTimeOut(callback,1000/60);
};
})();
var particleCount = 100,
particles = [];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var wW = window.innerWidth, wH = window.innerHeight;
canvas.width = wW;
canvas.height = wH;
function paintCanvas(){
ctx.fillStyle = "rgba(0,0,0,1)";
ctx.fillRect(0,0,wW,wH);
}
function Particle(){
this.x = Math.random() * wW;
this.y = Math.random() * wH;
var numx = Math.random()*2;
var numy = Math.random()*2;
numx *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
numy *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
this.vx = numx;
this.vy = numy;
this.radius = Math.random() * (Math.random()*5);
this.draw = function(){
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,false);
ctx.fill();
}
}
for (var i=0; i<particleCount; i++){
particles.push(new Particle());
}
function draw(){
paintCanvas();
for(var i = 0; i < particleCount; i++){
p = particles[i];
p.draw();
}
update();
}
function update(){
for (var i =0; i < particleCount; i++){
p = particles[i];
p.x += p.vx;
p.y += p.vy;
if(p.x + p.radius > wW){
p.x = p.radius;
}
else if(p.x - p.radius < 0){
p.x = wW - p.radius;
}
if(p.y + p.radius > wH){
p.y = p.radius;
}
else if(p.y - p.radius < 0){
p.y = wH - p.radius;
}
}
}
function animloop(){
draw();
requestAnimFrame(animloop);
}
animloop();
As Fiddle: https://jsfiddle.net/b8xbv7fu/