D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
headwinds
Full window
Github gist
enter exit merge
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500) const radius = 100; var sheepData = [ {color: "purple", radius, x: 10, y: radius, name: "purple"}, {color: "red", radius, x: 10, y: radius * 2, name: "red"}, {color: "pink", radius, x: 10, y: radius * 3, name: "pinkie"}, ] const blackSheep = {color: "black", radius: 10, x: 10, y: 100, name: "blacksheep"}; function update(data) { // DATA JOIN // Join new data with old elements, if any. var sheep = svg.selectAll("g") .data(data); // UPDATE // Update old elements as needed. const getColor = d => { //console.log("color: ",d) return d.color; } const getTranslate = d => { console.log("trans : ",d) return "translate (" + d.x + "," + d.y + ")"; } const getClass = d => { return d.name; } // sheep.attr("transform", getTranslate); // ENTER // Create new elements as needed. // // ENTER + UPDATE // After merging the entered elements with the update selection, // apply operations to both. let sheepG = sheep.enter().append("g") .attr("transform", getTranslate) .attr("class", getClass); sheepG .append("circle") // ENTER .attr("r", d => d.radius) .style("fill", getColor); const getEase = () => { const coinFlip = Math.random() * 100; return (coinFlip > 50) ? d3.easeSin : d3.easeBack; } sheep .merge(sheep) .transition() .ease(getEase()) .delay(500) .duration(2000) .attr("transform", getTranslate); // EXIT // Remove old elements as needed. sheep.exit().remove(); } update(sheepData); let count = 0; let int = setInterval( () => { //sheepData.push(blackSheep); function createNewSheep(sheep){ if (sheep.name === 'pinkie') return sheep; const newX = sheep.x + ( radius * count); //console.log("newX: ", newX); return {...sheep, x: newX}; } const newSheepData = sheepData.map(createNewSheep); update(newSheepData); if (count > 10) { clearInterval(int); } count++; }, 1000) </script> </body>
https://d3js.org/d3.v5.min.js