Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG keep new data visible

Tags:

javascript

svg

I render an SVG line that has a new point added to it every 50ms. After a few seconds, the line is off the page. How can I make my SVG keep the most recent part of the line in view, while moving the older part out of view

var $series = $('#series');
var data = [];

setInterval(function() {
  // Add random data step
  var newValue = Math.floor(Math.random() * 10) - 5;
  data.push(newValue)

  // Rerender line
  var newPoints = 'M10 50 ';
  data.forEach(function(y) {
    console.log(y);
    newPoints += "l 10 " + y + " ";
  });
  console.log(newPoints);
  $('#series').attr('d', newPoints);
}, 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg width="1000" height="500" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <path id="series" d="M10 250 l 10 10 l 10 20 l 10 50 l 10 -20" stroke="red" stroke-width="2" fill="none" />
</svg>
like image 816
Don P Avatar asked Mar 21 '26 06:03

Don P


1 Answers

var $series = $('#series');
var chart = $('#chartdiv').find('svg')[0];
var data = [];
var xmin = 0;
setInterval(function() {
  // Add random data step
  xmin = xmin + 10;
  var newValue = Math.floor(Math.random() * 10) - 5;
  data.push(newValue)

  // Rerender line
  var newPoints = 'M10 50 ';
  data.forEach(function(y) {
    //console.log(y);
    newPoints += "l 10 " + y + " ";
  });

  //console.log(newPoints);
  $('#series').attr('d', newPoints);
  if (xmin > 1000 )
    {
      var gmin = xmin - 1000;
      chart.setAttribute('viewBox', gmin + " 0 1000 500");
      }
}, 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='chartdiv'>
<svg viewBox="0 0 1000 500" width="1000" height="500" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <path id="series" d="M10 250 l 10 10 l 10 20 l 10 50 l 10 -20" stroke="red" stroke-width="2" fill="none" />
</svg>
</div>

Try this snippet above. I added a viewBox and increment the viewBox "x" value in each loop to move the viewing area live as you draw.

like image 64
Kevin Brown Avatar answered Mar 23 '26 20:03

Kevin Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!