D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
cmpolis
Full window
Github gist
simple Newtonian physics sim
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } svg { width:100%; height: 100% } </style> </head> <body> <script> var r = 8 var svg = d3.select("body").append("svg") .append('g') .attr('transform','translate(0,300)'); svg.append('line') .attr('x1', 0) .attr('x2', 1000) .attr('y1', r) .attr('y2', r) .attr('stroke','black'); // "drop" balls from random heights var xValues = d3.range(0,35).map(function(d) { return { y: Math.random() * 200, v: 0}; }); // var circleEnter = svg.selectAll('circle') .data(xValues).enter() .append('circle') .attr('r', r) .attr('cx', function(d, ndx) { return r + ndx * 30}) .attr('cy', function(d) { return -d.y; }) .attr('fill', 'steelblue') .attr('fill-opacity', 1); // update var circleSel = svg.selectAll('circle'); setInterval(function() { circleSel .attr('cy', function(d) { // gravity is '0.6' units, if floor is hit, dampen slightly // and velocity changes signs, last ternary is for case // to prevent ball from staying y < 0 d.v = d.y > 0 ? d.v-0.6 : (d.v < 0 ? -0.95*d.v : d.v-0.6); d.y += d.v; return -(d.y < 0 ? 0 : d.y); }) .attr('fill-opacity', function(d) { return Math.min(1, 0.2 + Math.abs(d.v/30)); }); }, 25); </script> </body>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js