javascript - D3 在屏幕上适配节点

标签 javascript d3.js svg

我有一个简单的 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/

相关文章:

javascript - 如何使用 jQuery 显示新内容

javascript - 为什么 'this' 在这种情况下不应该是这样?

javascript - 当用户单击模态触发器时,模态未打开

javascript - AngularJS $http 重定向状态码

unit-testing - 单元测试中的 d3 转换

jquery - nvd3.js不会从jquery获取数据

d3.js - 如何在 d3.js 中拖动路径

html - Base64 编码的 SVG 无法通过 HTML 标记中的内联样式或通过 CSS 中的类进行着色

javascript - D3 平移缩放溢出

javascript - Raphael.js 路径/渐变线?