Constantly creating and closing new paths is not good advice.
You must combine all the fills / strokes of the same style and execute them in one callback. The difference in performance between these approaches appears very quickly with an increase in the number of polygons.
The way to this is to move the pen and make a path construction call for each circle; stroke / fill at the end with one shot. However, there is a quirk. When you move the point to the center and draw a circle, you will still see a horizontal line of radius drawn from the center of the circle to the circle.
To avoid this artifact, instead of moving to the center, we go to a circle. This skips the drawing of the radius. In fact, all of these commands are designed to track the path, and there is no way to describe the gap without calling closePath ; usually moveTo does this, but the HTML5 canvas API does not. This is an easy way to solve this problem.
const pi2 = Math.PI * 2; const radius = 5; ctx.fillStyle = '#00a308'; ctx.beginPath(); for( let i=0, l=coords.length; i < l; i++ ) { const p = coords[i], x = px, y = py; ctx.moveTo( x + radius, y );
It is also worth considering, uses transformations and draws everything relative to the local coordinate system.
ctx.fillStyle = '#00a308'; ctx.beginPath(); for( let i=0, l=coords.length; i < l; i++ ) { const p = coords[i]; ctx.save(); ctx.translate( px + radius, py ); ctx.moveTo( 0, 0 ); ctx.arc( 0, 0, radius, 0, pi2 ); ctx.restore(); } ctx.stroke(); ctx.fill();
Adria
source share