Dynamic SVG Polyline

by godfrzero

HTML

<svg id='root' viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"></svg>

CSS

svg {
  border: solid thin black;
  height: 400px;
}

JavaScript

let $root = document.querySelector('#root'),
  svgGroup = document.createElement('g'),
  dataSource = [0, 10, 11, 10, 13, 10, 15, null, 12, 10, 19, 10, 21, 12, 8, null, 19,
  	10, 22, 32, 41, null, null, 48, 59, 69, 102, 98, 87, 92, 18, 12, 10, 2, 7, 4, 3, 1],
  xTick = 5,
  cursor = 0,
  polylinePoints = [];
  
function drawPolyline () {
  if (polylinePoints.length) {
    let polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');

		polyline.setAttribute('stroke', 'black');
    polyline.setAttribute('fill', 'none');
    polyline.setAttribute('points', polylinePoints.join(' '));
    
    // Attach the element to the DOM
    $root.appendChild(polyline);
    
    // Clear out the drawn points so we can start fresh in case there are new points coming in 
    polylinePoints = [];
  }
}

dataSource.forEach((mag) => {
  if (typeof mag === 'number') {
    polylinePoints.push(`${cursor},${200 - mag}`);
  }
  else {
		drawPolyline();
  }
  
  cursor += xTick;
});

// Flush the polyline array at the end, to catch points at the end of the array
drawPolyline();