/index.html Secret
Last active
November 19, 2016 13:36
D3 v3 force layout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<svg width="960" height="500"></svg> | |
<script src="https://d3js.org/d3.v3.min.js"></script> | |
<script> | |
const svg = d3.select('svg'); | |
const width = svg.attr('width'); | |
const height = svg.attr('height'); | |
// center marker | |
svg.append('circle') | |
.attr('r', 5) | |
.attr('cx', width / 2) | |
.attr('cy', height / 2); | |
const graph = { | |
nodes: [{}, {}, {}, {}, {}, {}], | |
links: [ | |
{source: 0, target: 1}, | |
{source: 1, target: 2}, | |
{source: 2, target: 0}, | |
{source: 4, target: 5} | |
] | |
}; | |
const link = svg.selectAll() | |
.data(graph.links) | |
.enter() | |
.append('line') | |
.attr('stroke', 'black') | |
.attr('stroke-width', '5px'); | |
const node = svg.selectAll() | |
.data(graph.nodes) | |
.enter() | |
.append('circle') | |
.attr('r', 50) | |
.attr('fill', 'red') | |
.attr('stroke', 'black') | |
.attr('stroke-width', '5px'); | |
const force = d3.layout.force() | |
.nodes(graph.nodes) | |
.links(graph.links) | |
.charge(-100) | |
.linkDistance(200) | |
.size([width, height]) | |
.on('tick', ticked); | |
function ticked() { | |
link | |
.attr('x1', d => d.source.x) | |
.attr('y1', d => d.source.y) | |
.attr('x2', d => d.target.x) | |
.attr('y2', d => d.target.y); | |
node | |
.attr('cx', d => d.x) | |
.attr('cy', d => d.y); | |
} | |
node.call(force.drag()); | |
force.start(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment