D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
easadler
Full window
Github gist
Force-Directed Layout from XML
forked from
mbostock
's block:
Force-Directed Layout from XML
<!DOCTYPE html> <style> .link line { stroke: #aaa; } .node circle { pointer-events: all; stroke: none; stroke-width: 40px; } </style> <svg width="960" height="500"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); var radius = d3.scaleSqrt() .domain([0, 20000]) .range([0, 20]); var link = svg.append("g") .attr("class", "link") .selectAll("line"); var node = svg.append("g") .attr("class", "node") .selectAll("circle"); var drag = d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended); var simulation = d3.forceSimulation() .force("link", d3.forceLink()) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)) .on("tick", ticked) .stop(); d3.xml("flare.xml", function(error, document) { if (error) throw error; var nodes = d3.select(document).selectAll("*").nodes(), links = nodes.slice(1).map(function(d) { return {source: d, target: d.parentNode}; }); link = link.data(links).enter().append("line"); node = node.data(nodes).enter().append("circle") .attr("r", function(d) { return radius(d.textContent) || 5; }) .call(drag); node.append("title") .text(function(d) { return d.tagName; }); simulation.nodes(nodes); simulation.force("link").links(links); simulation.restart(); }); function ticked() { link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); } function dragstarted(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x, d.fy = d.y; } function dragged(d) { d.fx = d3.event.x, d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null, d.fy = null; } </script>
https://d3js.org/d3.v4.min.js