D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
JoseMLopezSanz
Full window
Github gist
Graphene Structure
Built with
blockbuilder.org
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <canvas width="960" height="960"></canvas> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var n = 4*20; //multiple of 4, 7, 10, var m = 3*20; // at least 2 var nodes = d3.range( n * m ).map(function(i) { return { index: i }; }); var links = []; for (var y = 0; y < m; ++y) { for (var x = 0; x < n; ++x) { if (y > 0 & y%2==1 & x%4==0 ){ links.push({source: (y - 1) * n + (x+1), target: y * n + x}); }else if (y > 0 & y%2==1 & (x+1)%4==0){ links.push({source: (y - 1) * n + (x-1), target: y * n + x}); }else if(y>0 & y%2==0 & (x-1)%4==0){ links.push({source: (y - 1) * n + (x-1), target: y * n + x}); }else if(y>0 & y%2==0 & (x-2)%4==0){ links.push({source: (y - 1) * n + (x+1), target: y * n + x}); }; if (x > 0 & y%2==0 & (x-2)%4==0){ links.push({source: y * n + (x - 1), target: y * n + x}); }else if (x > 0 & y%2==1 & x%4==0 ){ links.push({source: y * n + (x - 1), target: y * n + x}); }; } } var simulation = d3.forceSimulation(nodes) .force("charge", d3.forceManyBody().strength(-25)) .force("link", d3.forceLink(links).strength(1).distance(1).iterations(15)) .on("tick", ticked); var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"), width = canvas.width, height = canvas.height; d3.select(canvas) .call(d3.drag() .container(canvas) .subject(dragsubject) .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); function ticked() { context.clearRect(0, 0, width, height); context.save(); context.translate(width / 2, height / 2); context.beginPath(); links.forEach(drawLink); context.strokeStyle = "#aaa"; context.stroke(); context.beginPath(); nodes.forEach(drawNode); context.fill(); context.strokeStyle = "#fff"; context.stroke(); context.restore(); } function dragsubject() { return simulation.find(d3.event.x - width / 2, d3.event.y - height / 2); } function dragstarted() { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d3.event.subject.fx = d3.event.subject.x; d3.event.subject.fy = d3.event.subject.y; } function dragged() { d3.event.subject.fx = d3.event.x; d3.event.subject.fy = d3.event.y; } function dragended() { if (!d3.event.active) simulation.alphaTarget(0); d3.event.subject.fx = null; d3.event.subject.fy = null; } function drawLink(d) { context.moveTo(d.source.x, d.source.y); context.lineTo(d.target.x, d.target.y); } //To do, only draw linked nodes. Maybe even try to delete them from the simulation function drawNode(d, i) { var r = 5; context.moveTo(d.x + r, d.y); context.arc(d.x, d.y, r, 0, 2 * Math.PI); }; </script> </body> </html>
https://d3js.org/d3.v4.min.js