D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
mukhtyar
Full window
Github gist
D3 - Enter, Update, Exit
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } #chart { margin: 3em; } .bar { background-color: blue; height: 20px; margin-top: 2px; } </style> </head> <body> <svg id="chart"></svg> <script> var rectWidth = 50; var chartHeight = 400; var chartWidth = 700; //var data = [200, 60, 100, 80, 10]; var svg = d3.select('#chart') .attr('height', chartHeight) .attr('width', chartWidth); function render(data){ // bars includes update selection var bars = svg.selectAll('rect') .data(data, d => d); // exit bars.exit().transition().remove(); // enter var enter = bars.enter().append('rect') .attr('width', rectWidth) .attr('stroke', '#FF00FF') .attr('stroke-width', '2'); // enter + update bars = enter.merge(bars).transition() .attr('x', function(d, i){ return i * rectWidth; }) .attr('y', function(d){ return chartHeight - d; }) .attr('height', function(d){ return d; }) .attr('fill', 'blue'); } setInterval(function(){ var data = []; var dataLength = Math.floor(Math.random() * 10) + 1; for (var i=0, t=dataLength; i<t; i++) { data.push(Math.round(Math.random() * t * 50)) } console.log(data); render(data); }, 3000); </script> </body>
https://d3js.org/d3.v4.min.js