绘制一棵树,如:
/*
root ->
    a
    b
    c ->
        d
        e
        f
    g ->
        h ->
            k
            m

*/

代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>

<BODY>
<div id="panel">

</div>

<SCRIPT LANGUAGE="JavaScript">
<!–
function Node(parent,label){
  this.parent = parent;
  this.label = label;
  this.children = [];
  if(parent != null)
    parent.children[parent.children.length] = this;
 
  this.x = 0;
  this.y = 0;

  this.totalH = 0;
  this.totalV = 0;
  this.index = 0;

  return this;
}

function calcTotal(node,index){
  node.index = index;
  var parent = node.parent;
  if(parent == null){
    node.totalH = 1;
  }else{
    node.totalH = parent.totalH + 1;
  }

  if(node.children.length == 0){
    node.totalV = 1;
  }else{
    var result = 0;
    for(var i=0;i<node.children.length;i++){
      var child = node.children[i];
      calcTotal(child,i);
      result += child.totalV;
    }
    node.totalV = result;
  }
}

function calcPosition(node){
  var parent = node.parent;
  if(parent == null){
    node.x = 0;
    node.y = node.totalV * _V_ /2;
  }else{
    node.x = node.totalH * _H_ ;
    var y = parent.y – parent.totalV * _V_ /2;
    for(var i=0;i<node.index;i++){
      var sibling = parent.children[i];
      y += sibling.totalV * _V_ ;
    }
    y += node.totalV * _V_ /2;
    node.y = y;
  }

  for(var i=0;i<node.children.length;i++){
    var child = node.children[i];
    calcPosition(child);
  }
}

var _H_ = 50;
var _V_ = 50;

function drawNode(node){
  var element = document.createElement("DIV");
  element.style.position = "absolute";
  var text = document.createTextNode(node.label);
  element.appendChild(text);
  element.style.left = node.x;
  element.style.top = node.y;
  var panel = document.getElementById("panel"); 
  panel.appendChild(element);

  for(var i=0;i<node.children.length;i++){
    var child = node.children[i];
    drawNode(child);
  }
}

/*
root ->
    a
    b
    c ->
        d
        e
        f
    g ->
        h ->
            k
            m

*/
var root = new Node(null,"root");
var a = new Node(root,"a");
var b = new Node(root,"b");
var c = new Node(root,"c");
var d = new Node(c,"d");
var e = new Node(c,"e");
var f = new Node(c,"f");
var g = new Node(root,"g");
var h = new Node(g,"h");
var k = new Node(h,"k");
var m = new Node(h,"m");

calcTotal(root,0);
calcPosition(root);
drawNode(root);

//–>
</SCRIPT>
</BODY>
</HTML>

效果:

连线都没画,懒人呀~


评论

该日志第一篇评论

发表评论

评论也有版权!