mardi 23 décembre 2014

Increase performance for 10,000 particles in html5 Canvas


I have two JS Fiddles, both with 10,000 snow flakes moving around but with two different approaches.


The first fiddle: http://ift.tt/1rfSfH2


Uses fillRect with a 4 by 4 white square, providing roughly 60 frames per second @ 10,000 snow flakes.


So i wondered if I could improve this and found a bit of information on HTML5Rocks' website regarding canvas performance. One such suggestion was to pre-render the snow flakes to canvases and then draw the canvases using drawImage.


The suggestion is here http://ift.tt/NwYyNS , namely under the title Pre-render to an off-screen canvas. Use ctrl+f to find that section.


So i tried their suggestion with this fiddle: http://ift.tt/1rfSfH4


How ever, i get about 3 frames per second @ 10,000 snow flakes. Which is very odd given jsPerf even shows a performance boost here using the same method http://ift.tt/1x99hWH


The code I used for pre-rendering is here:



//snowflake particles
var mp = 10000; //max particles
var particles = [];
for(var i = 0; i < mp; i++) {
var m_canvas = document.createElement('canvas');
m_canvas.width = 4;
m_canvas.height = 4;
var tmp = m_canvas.getContext("2d");
tmp.fillStyle = "rgba(255,255,255,0.8)";
tmp.fillRect(0,0,4,4);

particles.push({
x : Math.random()*canvas.width, //x-coordinate
y : Math.random()*canvas.height, //y-coordinate
r : Math.random()*4+1, //radius
d : Math.random()*mp, //density
img: m_canvas //tiny canvas
})
}
//Lets draw the flakes
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < particles.length; i++) {
var flake = particles[i];
ctx.drawImage(flake.img, flake.x,flake.y);
}
}


So I wondered why am i getting such horrendous frame rate? And is there any better way to get higher particle counts moving on screen whilst maintaining 60 frames per second?





Aucun commentaire:

Enregistrer un commentaire