Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Continuous Scrolling Graph with SVG HTML CSS

I have created a real-time graph where new data points are continuously being fed in and plotted.

Currently I am using requestAnimationFame() where I render the updated positions of the elements 30 times per second.

With many SVG elements, this can get a little slow.

What is the most efficient way to implement a continuously scrolling graph like this with SVG animations, CSS animations, or CSS transitions. (Without 3rd party libraries).

Thanks in advance.

like image 974
rustybeanstalk Avatar asked Nov 01 '22 10:11

rustybeanstalk


1 Answers

Here is a pretty good solution in a Fiddle.

It's from Mike Bostock and his awesome tutorial on using D3. In that tutorial; Mike explains how accomplish the Fiddle from scratch, but the important part for you is the redraw function:

function redraw() {

     var rect = chart.selectAll("rect")
         .data(data, function (d) {
         return d.time;
     });

     rect.enter().insert("rect", "line")
         .attr("x", function (d, i) {
         return x(i + 1) - .5;
     })
         .attr("y", function (d) {
         return h - y(d.value) - .5;
     })
         .attr("width", w)
         .attr("height", function (d) {
         return y(d.value);
     })
         .transition()
         .duration(1000)
         .attr("x", function (d, i) {
         return x(i) - .5;
     });

     rect.transition()
         .duration(1000)
         .attr("x", function (d, i) {
         return x(i) - .5;
     });

     rect.exit().transition()
         .duration(1000)
         .attr("x", function (d, i) {
         return x(i - 1) - .5;
     })
         .remove();

 } 

It will add a new rect based on incoming data and fade the oldest rect out, and so creates your desired scrolling action. This should be pretty easy to adapt to your needs but it does assume a fixed amount of rects.

It seems that you might want to have an unrestricted amount of rects on the screen at any given time from your question, but ultimately this is undesirable. You can set the amount of rects to display to largest amount that still allows your site to be performant. Anymore and it will crash for you and your users. Fading one in as one Fades out is more efficiently than continually loading once the svg count gets high enough.

like image 133
agconti Avatar answered Nov 09 '22 08:11

agconti