制作模块化d3js树节点

时间:2016-12-11 04:05:37

标签: d3.js

我从http://bl.ocks.org/d3noob/8375092

抓取了一个d3js树节点样本

我想要实现的是使这个模块化,以便我可以在html中有多个。 Javascript支持函数内部的函数,所以我只是把代码放在一个draw函数中,但它会使图表失真而没有任何错误。 任何想法如何解决它?

.node {
    cursor: pointer;
}
.node circle {
    fill: #fff;
    stroke: steelblue;
    stroke-width: 3px;
}
.node text {
    font: 12px sans-serif;
}
.link {
    fill: none;
    stroke: #ccc;
    stroke-width: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
  <div id="treenode_container_id1"></div>
  <div id="treenode_container_id2"></div>

<script>
function draw(id, data){
    var TREENODE_DURATION = 750;
	var margin = {top: 10, right: 10,
				  bottom: 10, left: 100};

	var width = 1200;
	var height = 200;

	var root;
	var tree = d3.layout.tree().size([height, width]);
	var diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });

	var svg = d3.select("#" + id).append("svg")
	  .attr("width", width + margin.right + margin.left)
	  .attr("height", height + margin.top + margin.bottom)
	  .attr("id", "svg_" + id)
	  .append("g")
	  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

	root = data[0];
	root.x0 = height / 2;
	root.y0 = 0;
	update(root);
	d3.select(self.frameElement).style("height", "200px");
	
	function wrap(text, width) {
	  // wraps long labels given the maximum width
	  // where words are split by spaces
	  text.each(function() {
		var text = d3.select(this),
			words = text.text().split(/\s+/).reverse(),
			word,
			line = [],
			lineNumber = 0,
			lineHeight = 0.7, // ems
			y = text.attr("y"),
			dy = parseFloat(text.attr("dy"))/2,
			tspan = text.text(null).append("tspan").attr("x", 10).attr("y", y+20).attr("dy", dy + "em");
		while (word = words.pop()) {
		  line.push(word);
		  tspan.text(line.join(" "));
		  if (tspan.node().getComputedTextLength() > width) {
			line.pop();
			tspan.text(line.join(" "));
			line = [word];
			tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
		  }
		}
	  });
	}

	function update(source) {
	  // Compute the new tree layout.
	  var nodes = tree.nodes(root).reverse(),
		  links = tree.links(nodes);

	  // Normalize for fixed-depth.
	  nodes.forEach(function(d) { d.y = d.depth * 180; });

	  // Update the nodes…
	  var i;
	  var node = svg.selectAll("g.node")
		.data(nodes, function(d) { return d.id || (d.id = ++i); });

	  // Enter any new nodes at the parent's previous position.
	  var nodeEnter = node.enter().append("g")
		.attr("class", "node")
		.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
		.on("click", click);

	  nodeEnter.append("circle")
		  .attr("r", 1e-6)
		  .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

	  nodeEnter.append("text")
		  .attr("x", function(d) { return d.children || d._children ? -13 : 13; })
		  .attr("dy", ".35em")
		  .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
		  .text(function(d) { return d.name; })
		  .style("fill-opacity", 1e-6);

	  // Transition nodes to their new position.
	  var nodeUpdate = node.transition()
		  .duration(TREENODE_DURATION)
		  .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

	  nodeUpdate.select("circle")
		  .attr("r", 10)
		  .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

	  nodeUpdate.select("text")
		  .style("fill-opacity", 1);
	  

	  // Transition exiting nodes to the parent's new position.
	  var nodeExit = node.exit().transition()
		  .duration(TREENODE_DURATION)
		  .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
		  .remove();

	  nodeExit.select("circle")
		  .attr("r", 1e-6);

	  nodeExit.select("text")
		  .style("fill-opacity", 1e-6);

	  // Update the links…
	  var link = svg.selectAll("path.link")
		  .data(links, function(d) { return d.target.id; });

	  // Enter any new links at the parent's previous position.
	  link.enter().insert("path", "g")
		  .attr("class", "link")
		  .attr("d", function(d) {
			var o = {x: source.x0, y: source.y0};
			return diagonal({source: o, target: o});
		  });

	  // Transition links to their new position.
	  link.transition()
		  .duration(TREENODE_DURATION)
		  .attr("d", diagonal);

	  // Transition exiting nodes to the parent's new position.
	  link.exit().transition()
		  .duration(TREENODE_DURATION)
		  .attr("d", function(d) {
			var o = {x: source.x, y: source.y};
			return diagonal({source: o, target: o});
		  })
		  .remove();

	  // Stash the old positions for transition.
	  nodes.forEach(function(d) {
		d.x0 = d.x;
		d.y0 = d.y;
	  });
	}

	// Toggle children on click.
	function click(d) {
	  
	  if (d.children) {
		d._children = d.children;
		d.children = null;
	  } else {
		d.children = d._children;
		d._children = null;
	  }
	  update(d);
	  
	}
}

// +++++ Generate 2 drawings:
var data1 = [{"name":"Top Level","parent":"null","children":[{"name":"Level 2: A","parent":"Top Level","children":[{"name":"Son of A","parent":"Level 2: A"},{"name":"Daughter of A","parent":"Level 2: A"}]},{"name":"Level 2: B","parent":"Top Level"}]}];

var data2 = [{'name': 'food', 'parent': 'null', 'children': [{'name': 'vegetables', 'parent': 'food', 'children': [{'name': 'mint', 'parent': 'vegetables'}, {'name': 'asparagus', 'parent': 'vegetables'}, {'name': 'eggplant', 'parent': 'vegetables'}, {'name': 'avocado', 'parent': 'vegetables'}, {'name': 'braccoli', 'parent': 'vegetables'}]}, {'name': 'fruits', 'parent': 'food', 'children': [{'name': 'apple', 'parent': 'fruits'}, {'name': 'orange', 'parent': 'fruits'}, {'name': 'banana', 'parent': 'fruits'}]}]}];

draw("treenode_container_id1", data1);
draw("treenode_container_id2", data2);
// +++++++++++++++++++++++++++

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您没有将初始值设置为i,因此每个节点都获得id NaN

var i = 0;