Reputation: 10158
I'm trying to find the most efficient way to draw thousands of lines on a page.
I have a database that contains every single point that I'd like to draw and I can pull these into a python list of coordinates that looks like: [[0,0],[200,100],[400,250]]. This list includes about 2000 points. And I'd like to connect each of these points together with a line segment forming 1 big line. Each segment may need to be a different colour
On every page, I'd like to draw 2-3 of these big lines (so there will be about 2000-6000 points per page)
My 2 questions are:
What is the most efficient way to draw this many lines without slowing down the browser?
Is there a way to make the resulting image/canvas zoomable so users can zoom in on specific sections of this line and navigate around?
Im currently using some test code like this, but is there a more efficient way to do this:
<canvas id="myCanvas" width="400" height="400"
style="border:1px solid #ffffff;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.strokeStyle = '#ff0000';
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(200,100);
ctx.lineTo(400,250);
ctx.strokeStyle = '#6b44cc';
ctx.stroke();
ctx.closePath();
</script>
Upvotes: 2
Views: 709
Reputation: 4417
Compiling these points to an SVG file seems like the most efficient option. If I understand your question correctly, you already have a database of points you'd like to draw. This means that there is no need to generate this image on the fly.
I would guess a precompiled SVG image would load a lot faster than lines drawn on a canvas. Canvas may be faster at generating images on the fly, but if you can generate your image before hand, this will save you a lot of time in the browser. SVG would also be zoomable so I think this best fits your criteria.
Here's an example of a library you could use to zoom and pan your SVG
EDIT:
I created a large SVG image with 100000 lines (similar to dwana's canvas one here: jsfiddle.net/dqkksbz6/2) and found that my guess was wrong. As MarkE points out, a huge amount of DOM nodes does have a significant impact on browser performance. SVG is actually slower. Using a canvas is a lot faster and doesn't break the browser the way a huge SVG does.
Still, my original point still stands about generating the image before it's requested. MarkE's comment is very helpful and maybe there's something in that. You could generate a PNG which then switches out to a small SVG of the relevant area once a certain zoom level is reached. This would be quite a lot of work to put together, but I can't think of a better way to optimise for both speed and quality.
Upvotes: 2