I have a lot of elements and mousemove method which, when selecting an item does redraw canvas.
function redraw(ctx) { // ctx - canvas context
if (!needRedraw)
return;
ctx.save();
ctx.clearRect(0, 0, w, h);
drawItems(ctx);
ctx.restore();
}
function drawItems(ctx) {
var l = nodes.length(); // array of elements for drawing (from 100 to 100000)
for(var i = 0; i < l; i++) {
var item = nodes[i];
ctx.beginPath();
ctx.strokeStyle = colors(item.type);
ctx.fillStyle = fill(item);
ctx.arc(item.x, item.y, item.r, 0, Math.PI * 2, true);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
How to optimize this process, since it runs through all the elements of this highly expensive?
May be used async method, but i’m not understand how to apply him?
Your calls to
save,restoreandclosePathdo nothing as they are written. Remove them.saveandrestorecopy alllll of the canvas state and should be rarely if ever used. In a perfect performant world the only reason you’ll ever need to use them is to reset the clipping region.Draw one and only one path, and fill (and stroke) it only once, at the end.
Like this:
Depending on what you’re doing its very possible there are more optimizations to be had, but that should help!
Hope your project goes well.