【发布时间】:2016-06-04 02:59:02
【问题描述】:
我想要一个我的力导向图版本,它对每个节点使用正方形而不是圆形。我用来执行此操作的代码可以正常工作,但它不是以正方形为中心,而是在每个正方形的左上角绘制每个正方形,其中圆的中心将位于圆形节点中。这意味着我的文本标签不再居中。如何调整矩形对象的 x 和 y 位置以占据圆形的相同空间?
我用于圆形和方形节点的代码如下。
function nearest(value, min, max, steps) {
var zerone = Math.round((value - min) * steps / (max - min)) / steps; // bring to 0-1 range
return zerone * (max - min) + min;
}
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.attr('stroke', function(d) {return d.color; })
.attr('stroke-width', 1)
.on("mouseover", function(d) {
d3.select(this).attr('stroke-width', 2);
})
.on("mouseout", function(d) {
d3.select(this).attr('stroke-width',1);
});
var node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", function (d) nearest((Math.log(d.weight) *10), 10, 50, 5) || 10;})
.style('fill', function(d) { return d.color; })
.on("mouseover", function(d) {
link.style('stroke-width', function(l) {
if (d === l.target || d === l.source)
return 2;
})
link.style('stroke', function(l) {
if (d === l.target || d === l.source)
return 'aqua';
})
.duration(150);
})
.on("mouseout", function(d) {
link.style('stroke-width', 1)
link.style('stroke', function(d) {return d.color; })
.duration(150);
});
node.append("rect")
.attr("width", function (d) {return nearest(((Math.log(d.weight) *10)), 10, 50, 5) * 2 || 10;})
.attr("height", function (d) {return nearest(((Math.log(d.weight) *10)), 10, 50, 5) * 2 || 10;})
.style('fill', function(d) { return d.color; })
.on("mouseover", function(d) {
link.style('stroke-width', function(l) {
if (d === l.target || d === l.source)
return 2;
})
link.style('stroke', function(l) {
if (d === l.target || d === l.source)
return 'aqua';
})
.duration(150);
})
.on("mouseout", function(d) {
link.style('stroke-width', 1)
link.style('stroke', function(d) {return d.color; })
.duration(150);
});
【问题讨论】:
标签: d3.js