我有一个简单的 D3 图表,但我很挣扎,但由于某种原因,节点不会留在 svg 的范围内。我给了它们一个高度和宽度,当节点呈现时,它们会超出所述高度和宽度,因此是不可见的。
let height = 500;
let width = 960;
this.svg = d3.select("networkView").append("svg")
.attr("width", width)
.attr("height", height);
this.force = d3.layout.force()
.gravity(.05)
.charge(-240)
.linkDistance(50)
.size([width, height]);
let node = this.svg.selectAll(".node")
.data(jsonNodes)
.enter().append("g")
.attr("class", "node")
.call(this.force.drag);
node.append("circle")
.attr("r","10");
node.append("text")
.attr("dx", 0)
.attr("dy", "2.5em")
.text(function(d) { return d.name })
.call(this.force.drag);
this.force
.nodes(jsonNodes)
.start();
this.force.on("tick", function() {
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
最佳答案
这里有个概念上的误区。 size()
不会限制您的节点。根据API ,它将简单地:
...set the available layout size to the specified two-element array of numbers representing x and y [...] The size affects two aspects of the force-directed layout: the gravitational center, and the initial random position.
一个可能的解决方案是使用这个简单的数学:
node.attr("transform", function(d) {
return "translate(" + (d.x = Math.max(0, Math.min(width, d.x))) + ","
+ (d.y = Math.max(0, Math.min(height, d.y))) + ")"
});
如果你想考虑你的圆圈的半径(现在是 10
),它变成:
node.attr("transform", function(d) {
return "translate(" + (d.x = Math.max(10, Math.min(width - 10, d.x))) + ","
+ (d.y = Math.max(10, Math.min(height - 10, d.y))) + ")"
});
关于javascript - D3 在屏幕上适配节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212862/