sylar32
sylar32

Reputation: 177

Canvas - how to fill all circles at once, not one by one

I have while loop drawing circles one by one:

actx.shadowColor = 'rgba(0, 0, 0, 1)';
while (len--) {
   var point = data[len];

   actx.beginPath();
   actx.arc(point[0] - 15000, point[1] - 15000, 10, 0, Math.PI * 2);
   actx.closePath();
   actx.fill();
}

It seems a little bit slow for me, so I am thinking how it could be optimized. I have found that the fill() function takes the longest, so I have tried put it after the loop, but it draws only the last circle.

  1. Is there any way how to fill all the circles at once?
  2. Or is there any other, faster method?

Upvotes: 0

Views: 69

Answers (1)

markE
markE

Reputation: 105015

Some optimizations:

  • Calculate Math.PI*2 once outside the loop instead of every time inside the loop
  • Put beginPath before the loop
  • Draw an arc + closePath inside the loop (you are creating many circle subpaths inside the loop)
  • put fill after the loop to draw all the subpaths at once

Refactored code:

// test data
var data=[];
for(var i=0;i<100;i++){data.push([i+15000+30,i+15000+30]);}

// calculate PI2 outside the loop instead of every time in the loop
var PI2=Math.PI*2;

actx.shadowColor = 'rgba(0, 0, 0, 1)';

// beginpath once outside the loop
actx.beginPath();
var len=data.length;
while (len--) {
   var point = data[len];

   // draw
   actx.arc(point[0]-15000, point[1]-15000,10,0,PI2);
   // closepath will close the current circle's subpath
   actx.closePath();

}           
// just fill once when done drawing
actx.fill();

Upvotes: 1

Related Questions