【发布时间】:2017-06-18 12:11:33
【问题描述】:
我正在用 D3 制作一个力有向图,并让它与节点的 svg 圆一起工作。但是,当我将 div 与 CSS left 和 top 属性结合使用时,节点就错位了。我无法弄清楚我在这里做错了什么。我使用强制 D3 生成的 x 和 y 坐标作为 left 和 top 属性,但也许这不是要走的路?
这是我的 JS:
var url = "https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json";
d3.json(url, function(json){
var data = json;
var margin = {top: 40, right: 40, bottom: 40, left: 40};
var w = 1000 - margin.left - margin.right;
var h = 1000 - margin.top - margin.bottom;
var svg = d3.select("#chart")
.append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var nodes = data.nodes;
var links = data.links;
//Create a force layout object and define its properties
var force = d3.layout.force()
.size([w,h])
.nodes(nodes)
.links(links);
force.linkDistance(h/20);
force.charge(-120)
var link = svg.selectAll(".link")
.data(links)
.enter()
.append("line")
.attr("class", "link");
var node = d3.select("#chart").selectAll(".node")
.data(nodes)
.enter()
.append("div")
force.on("end", function(){
//set node and link position attributes once force calculations have finished
//position the nodes
node.style("left", function(d){
return d.x + "px";
})
.style("top", function(d){
return d.y + "px";
})
.attr("class", function(d){
return "flag flag-" + d.code + " node";
})
.attr("src", "https://res.cloudinary.com/dettjqo9j/image/upload/v1485942660/flags_xf9dde.png");
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;
})
})//force.on
force.start();
//let the force start its calculations
})
我的 CSS:
svg {
background-color: white;
box-shadow: 0 0 10px #888888;
}
.link {
stroke: #2c3e50;
stroke-width: 2px;
}
.flag {
display: inline-block;
position:absolute;
width: 16px;
height: 11px;
background: url('https://res.cloudinary.com/dettjqo9j/image/upload/v1485942660/flags_xf9dde.png') no-repeat;
}
.flag.flag-ml {
background-position: -224px -88px;
}
到目前为止在 codepen 上的图表:
【问题讨论】:
标签: javascript css d3.js svg data-visualization