Controling Line Length D3.js
I'm using the following code to produce a circle surrounded by other circles, which are all connected to the main one via element. I'm trying to make them unevenly spa
Solution 1:
There are several ways to achieve what you want. But the most important thing is remembering that linkDistance
accepts a function.
For instance, in this snippet, I'm setting the distance in the data array for the links:
varlinks= [{
source:1,
target:0,
distance:50
}, {
source:2,
target:0,
distance:20
}, {
source:3,
target:0,
distance:150
}, {
source:4,
target:0,
distance:80
}, {
source:5,
target:0,
distance:40
}]
And using it in the force:
.linkDistance(d=>d.distance)
Check the snippet:
var nodes = [{
name: "a"
}, {
name: "b"
}, {
name: "c"
}, {
name: "d"
}, {
name: "e"
}, {
name: "f"
}];
var links = [{
source: 1,
target: 0,
distance: 50
}, {
source: 2,
target: 0,
distance: 20
}, {
source: 3,
target: 0,
distance: 150
}, {
source: 4,
target: 0,
distance: 80
}, {
source: 5,
target: 0,
distance: 40
}]
var width = 400
height = 300;
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([width, height])
.linkDistance(d => d.distance)
.charge(-1000)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link")
.data(force.links())
.enter().append("line")
.attr("stroke", "black")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", (d,i) => i ? 10 : 16)
.style("fill", (d,i) => i ? "teal" : "brown");
functiontick() {
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("transform", function(d) {
return"translate(" + d.x + "," + d.y + ")";
});
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Post a Comment for "Controling Line Length D3.js"