我在学习如何缩放方面度过了一段地狱般的时光。为了学习,我一直在尝试进行树状图缩放。我正在使用这个 jsfiddle 示例(http://jsfiddle.net/6kEpp/1/)并尝试将其应用于没有折叠节点的树状图。我从 Bostock 的径向树状图示例中提取了这个树状图,并将其理顺。
我很抱歉添加了整个脚本。
调试时,我被告知缩放未在“.on(“缩放”,缩放))中定义;“。我见过没有定义 var zoom 的例子。
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 2000 - margin.right - margin.left,
height = 2000 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, width])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, height])
.range([height, 0]);
var tree = d3.layout.tree()
.size([height, width])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1,8])
.on("zoom", zoom));
d3.json("flare.json", function(error, root) {
var nodes = tree.nodes(root),
links = tree.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dy", ".31em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; });
// zoom in / out
function zoom(d) {
var nodes = svg.selectAll(".node");
nodes.attr("transform", transform);
// Update the links...
var link = svg.selectAll(".link");
link.attr("d", translate);
}
function transform(d) {
return "translate(" + x(d.y) + "," + y(d.x) + ")";
}
function translate(d) {
var sourceX = x(d.target.parent.y);
var sourceY = y(d.target.parent.x);
var targetX = x(d.target.y);
var targetY = (sourceX + targetX)/2;
var linkTargetY = y(d.target.x0);
var result = "M"+sourceX+","+sourceY+" C"+targetX+","+sourceY+" "+targetY+","+y(d.target.x0)+" "+targetX+","+linkTargetY+"";
//console.log(result);
return result;
}
});
d3.select(self.frameElement).style("height", "800px");
</script>
</body>
</html>