d3自定义树图备份

//全局设置同步
$.ajaxSetup({
 async: false
    });
    var tree = CollapsibleTree("body");
    tree.init("/sistem/getdata/drawing/roottree?entName="+comName+"&type="+getDataType);
  //回复异步
$.ajaxSetup({
 async: true

    });


var CollapsibleTree = function(elt) {



var company_open = "../../images/cross.png";//+号
var company_close = "../../images/minus.png";//-号



  var m = [20, 50, 20, 50],
      w = 1366 - m[1] - m[3],
      h = 1000 - m[0] - m[2],
      i = 0,
      root,_root,lasetNode;//保存点击到的2级节点
  var tree = d3.layout.tree()
      // .size([h, w]);
      .size([w, h]);
  function zoom() {
//      visa.attr("transform", "scale(" + d3.event.scale + ")");
    }
// var zoomListener = d3.behavior.zoom().scaleExtent([0.5, 3]).on("zoom", zoom);
  var parentdiagonal = d3.svg.diagonal()
      .projection(function(d) { return [d.x, -d.y]; });


  var childdiagonal = d3.svg.diagonal()
      .projection(function(d) { return [d.x, d.y]; });


  var visa = d3.select(elt).append("svg:svg")
      .attr("width", w + m[1] + m[3])
      .attr("height", h + m[0] + m[2]);
//     .call(zoomListener);
  
  var vis = visa.append("svg:g")
  .attr("transform", "translate(30,"+h/5+")"); // bidirectional-tree
  
  //背景图片
  var defs = vis.append("defs").attr("id", "imgdefs")
  //-号图片
var company_close_nodes = defs.append("pattern")
.attr("id", "company_close")
.attr("height", 1)
.attr("width", 1)
company_close_nodes.append("image")
.attr("x", 0)
.attr("y", 0)
.attr("width",26)
.attr("height", 26)
.attr("href", company_close)
//+号
var company_open_nodes = defs.append("pattern")
.attr("id", "company_open")
.attr("height", 1)
.attr("width", 1)
company_open_nodes.append("image")
.attr("x", 0)
.attr("y", 0)
.attr("width",26)
.attr("height", 26)
.attr("href", company_open)


  var that = {
    init: function(url) {
      var that = this;
      d3.json(url, function(json) {
     _loading.close();
        root = json.data;
        _root = root;
//        console.info(JSON.stringify(root));
         root.x0 = h / 2 ;
         root.y0 = 0;
//        root.children.forEach(that.toggleAll);
        //根节点上下画图
        that.updateBoth(root);
      });
    },
    updateBoth: function(source) {
      var duration = d3.event && d3.event.altKey ? 5000 : 500;


      var nodes = tree.nodes(root).reverse();
      
      rootNods = nodes;
      
      nodes.forEach(function(d) { d.y = d.depth * 100; });
      
      var node = vis.selectAll("g.node")
          .data(nodes, function(d) { return d.id || (d.id = ++i); });


      var nodeEnter = node.enter().append("svg:g")
          .attr("class", "node")
          .attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
//          .on("mousemove",function(d,i){//移入节点   显示文本内容
//          var text = d3.select(this)[0][0].lastChild;
//          text.style.display = "block";
//          })
//          .on("mouseleave", function(d,i) {//移除节点  隐藏文本内容
//          var text = d3.select(this)[0][0].lastChild;
//          text.style.display = "none";
// })
          .on("click", function(d) {
         //绑定点击时间   isparent =false  子节点向下画图  反之向上画图
         if(d == root){
         that.toggle(_root);
         }else if(d.isparent){ // 跟节点点击事件  归属于父节点操作
         lasetNode = d; //保存点击到的2级节点
         that.togglePrent(d);
         }else{
         lasetNode = d;
         that.toggleChild(d);
         }
        });


      nodeEnter.append("svg:circle")
          .attr("r", 13)
          .style("fill", function(d) { 
          return "url(#company_open)";
         });


      nodeEnter.append("svg:text")
          .attr("x", function(d) {
            if( that.isParent(d) ) {
              return -14;
            } else {
              return d.children || d._children ? -14 : 14;
            }
          })
          .attr("dy", ".35em")
          .style('fill', "#b8b6b6")
//          .style("display", function(d){
// return "none";
// })
          .attr("text-anchor", function(d) {
            if( that.isParent(d) ) {
              return "end";
            } else {
              return d.children || d._children ? "end" : "start";
            }
          })
          .attr("transform",function(d) {
            if( d != root ) {
              if( that.isParent(d) ) {
                return "rotate(90)";
              } else {
                return "rotate(90)";
              }            
            }
          })
          .text(function(d) { return d.name; })
          .style("fill-opacity", 8);
     
     
     
      var nodeUpdate = node.transition()
          .duration(duration)
          .attr("transform", function(d) {
            if( that.isParent(d) ) {
              return "translate(" + d.x + "," + -d.y + ")";
            } else {
              return "translate(" + d.x + "," + d.y + ")";
            }
          });


      nodeUpdate.select("circle")
          .attr("r", 13)
          .style("fill", function(d) { 
         if(d.parents ==null || d.children == null){
         return "url(#company_open)";
         }else{
         return "url(#company_close)";
         }
          });


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


      var nodeExit = node.exit().transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + source.x + "," + source.y + ")"; })
          .remove();


      nodeExit.select("circle")
          .attr("r", 13);


      nodeExit.select("text")
          .style("fill-opacity", 13);
//
      var link = vis.selectAll("path.link")
          .data(tree.links_parents(nodes).concat(tree.links(nodes)), function(d) { return d.target.id; });


      link.enter().insert("svg:path", "g")
          .attr("class", "link")
          .attr("d", function(d) {
            var o = {x: source.x0, y: source.y0};
            if( that.isParent(d.target) ) {
              return parentdiagonal({source: o, target: o});
            } else {
              return childdiagonal({source: o, target: o});
            }
          })
        .transition()
          .duration(duration)
          .attr("d", function(d) {
            if( that.isParent(d.target) ) {
              return parentdiagonal(d);
            } else {
              return childdiagonal(d);
            }
          })
//
      link.transition()
          .duration(duration)
          .attr("d", function(d) {
            if( that.isParent(d.target) ) {
              return parentdiagonal(d);
            } else {
              return childdiagonal(d);
            }
          })


      link.exit().transition()
          .duration(duration)
          .attr("d", function(d) {
            var o = {x: source.x, y: source.y};
            if( that.isParent(d.target) ) {
              return parentdiagonal({source: o, target: o});
            } else {
              return childdiagonal({source: o, target: o});
            }
          })
          .remove();


      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });
    },
    updateParents: function(source) {
      var duration = d3.event && d3.event.altKey ? 5000 : 500;


      var nodes =  tree.nodes(_root).reverse();


      nodes.forEach(function(d) { d.y = d.depth * 100; });


      var node = vis.selectAll("g.node")
          .data(nodes, function(d) { return d.id || (d.id = ++i); });


      var nodeEnter = node.enter().append("svg:g")
          .attr("class", "node")
          .attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
//          .on("mousemove",function(d,i){//移入节点   显示文本内容
//          var text = d3.select(this)[0][0].lastChild;
//          text.style.display = "block";
//          })
//          .on("mouseleave", function(d,i) {//移除节点  隐藏文本内容
//          var text = d3.select(this)[0][0].lastChild;
//          text.style.display = "none";
// })
          .on("click", function(d) { that.togglePrent(d); });//that.updateParents(d);


      nodeEnter.append("svg:circle")
          .attr("r",13)
          .style("fill", function(d) { 
         return "url(#company_open)";
          });


      nodeEnter.append("svg:text")
     .attr("x", function(d) {
       if( that.isParent(d) ) {
         return -14;
       } else {
         return d.children || d._children ? -14 : 14;
       }
     })
     .attr("dy", ".35em")
     .style('fill', "#b8b6b6")
//      .style("display", function(d){
// return "none";
// })
     .attr("text-anchor", function(d) {
       if( that.isParent(d) ) {
         return "end";
       } else {
         return d.children || d._children ? "end" : "start";
       }
     })
     .attr("transform",function(d) {
       if( d != root ) {
         if( that.isParent(d) ) {
           return "rotate(90)";
         } else {
           return "rotate(90)";
         }            
       }
     })
     .text(function(d) { return d.name; })
     .style("fill-opacity", 8);
     
      var nodeUpdate = node.transition()
     .duration(duration)
     .attr("transform", function(d) {
       if( that.isParent(d) ) {
         return "translate(" + d.x + "," + -d.y + ")";
       } else {
         return "translate(" + d.x + "," + d.y + ")";
       }
     });


      nodeUpdate.select("circle")
          .attr("r", 13)
          .style("fill", function(d) {
         if(d.parents == null){
         return "url(#company_open)";
         }else{
         return "url(#company_close)";
         }
          });


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


      var mynode = node.exit().transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + source.x + "," + source.y + ")"; })
          .remove();
      
      mynode.select("circle")
          .attr("r", 13);


      mynode.select("text")
          .style("fill-opacity", 8);


       lasetlink = vis.selectAll("path.link")
      .data(tree.links_parents(nodes).concat(tree.links(nodes)), function(d) { return d.target.id; });
      
       lasetlink.enter().insert("svg:path", "g")
     .attr("class", "link")
     .attr("d", function(d) {
       var o = {x: source.x0, y: source.y0};
       if( that.isParent(d.target) ) {
         return parentdiagonal({source: o, target: o});
       } else {
         return childdiagonal({source: o, target: o});
       }
     })
   .transition()
     .duration(duration)
     .attr("d", function(d) {
       if( that.isParent(d.target) ) {
         return parentdiagonal(d);
       } else {
         return childdiagonal(d);
       }
     });


       lasetlink.transition()
     .duration(duration)
     .attr("d", function(d) {
       if( that.isParent(d.target) ) {
         return parentdiagonal(d);
       } else {
         return childdiagonal(d);
       }
     })


     
      lasetlink.exit().transition()
          .duration(duration)
          .attr("d", function(d) {
            var o = {x: source.x, y: source.y};
            if( that.isParent(d.target) ) {
              return parentdiagonal({source: o, target: o});
            } else {
              return childdiagonal({source: o, target: o});
            }
          })
          .remove();


      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });
    },    
    updateChildren: function(source) {
      var duration = d3.event && d3.event.altKey ? 5000 : 500;


      var nodes = tree.nodes(_root).reverse();
      
      nodes.forEach(function(d) { d.y = d.depth * 100; });


      var node = vis.selectAll("g.node")
          .data(nodes, function(d) { return d.id || (d.id = ++i); });


      var nodeEnter = node.enter().append("svg:g")
          .attr("class", "node")
          .attr("transform", function(d) { 
         return "translate(" + source.x0 + "," + source.y0 + ")"; 
//          return "translate(" + (source.x0 - 90) + "," + (source.y0-90) + ")"; //原来节点缩小90
//          return "rotate(" + (source.x0 - 90) + ")translate(" + source.y0 + ")";
         })
//           .on("mousemove",function(d,i){//移入节点   显示文本内容
//           var text = d3.select(this)[0][0].lastChild;
//          text.style.display = "block";
//          })
//          .on("mouseleave", function(d,i) {//移除节点  隐藏文本内容
//          var text = d3.select(this)[0][0].lastChild;
//          text.style.display = "none";
// })
          .on("click", function(d) {  that.toggleChild(d);  });//that.updateChildren(d);


      nodeEnter.append("svg:circle")
          .attr("r", 13)
          .style("fill", function(d) {
         return "url(#company_open)";
          });


      var child_node =  nodeEnter.append("svg:text")
     .attr("x", function(d) {
         if( that.isParent(d) ) {
           return -14;
         } else {
           return d.children || d._children ? -14 : 14;
         }
       })
       .attr("dy", ".35em")
       .style('fill', "#b8b6b6")
//        .style("display", function(d){
// return "none";
// })
       .attr("text-anchor", function(d) {
         if( that.isParent(d) ) {
           return "end";
         } else {
           return d.children || d._children ? "end" : "start";
         }
       })
       .attr("transform",function(d) {
         if( d != root ) {
           if( that.isParent(d) ) {
             return "rotate(90)";
           } else {
             return "rotate(90)";
           }            
         }
       })
       .text(function(d) { return d.name; })
       .style("fill-opacity", 8);
      
      var nodeUpdate = node.transition()
     .duration(duration)
     .attr("transform", function(d) {
       if( that.isParent(d) ) {
         return "translate(" + d.x + "," + -d.y + ")";
       } else {
         return "translate(" + d.x + "," + d.y + ")";
       }
     });


      nodeUpdate.select("circle")
          .attr("r",13)
          .style("fill", function(d) {
         if(d.children == null){
         return "url(#company_open)";
         }else{
         return "url(#company_close)";
         }
          });


      nodeUpdate.select("text")
          .style("fill-opacity", 1);
      
    
      //展开当前节点
     var mynode = node.exit().transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + source.x + "," + source.y + ")"; })
          .remove();
     
     
     
      mynode.select("circle")
          .attr("r", 13);


      mynode.select("text")
          .style("fill-opacity", 8);


      lasetlink = vis.selectAll("path.link")
          .data(tree.links_parents(nodes).concat(tree.links(nodes)), function(d) { return d.target.id; });


      lasetlink.enter().insert("svg:path", "g")
     .attr("class", "link")
     .attr("d", function(d) {
       var o = {x: source.x0, y: source.y0};
       if( that.isParent(d.target) ) {
         return parentdiagonal({source: o, target: o});
       } else {
         return childdiagonal({source: o, target: o});
       }
     })
   .transition()
     .duration(duration)
     .attr("d", function(d) {
       if( that.isParent(d.target) ) {
         return parentdiagonal(d);
       } else {
         return childdiagonal(d);
       }
     });


      lasetlink.transition()
     .duration(duration)
     .attr("d", function(d) {
       if( that.isParent(d.target) ) {
         return parentdiagonal(d);
       } else {
         return childdiagonal(d);
       }
     })


    lasetlink.exit().transition()
         .duration(duration)
         .attr("d", function(d) {
           var o = {x: source.x, y: source.y};
           if( that.isParent(d.target) ) {
             return parentdiagonal({source: o, target: o});
           } else {
             return childdiagonal({source: o, target: o});
           }
         })
         .remove();


      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });
    },


    isParent: function(node) {
      if( node.parent && node.parent != root ) {
     return this.isParent(node.parent);
      } else
      if( node.isparent ) {
        return true;
      } else {
        return false;
      }
    },
    
    //父节点画图   上画图
    togglePrent:function(d){
    d.children = null;
    var name = d.name;
 var ind = name.indexOf("-");
 if(ind>0){
 name = name.substring(0,ind);
 }
 if (d.parents) {
//收缩
        d._parents = d.parents;
        d.parents = null;
      } else {
      if(d._parents != null){
      d.parents = d._parents;
        d._parents = null;
      }else{
      _loading=new PublicLoading();
  _loading.open("正在加载,请稍后...");
    //检索一次
     $.ajax({
    url:"/sistem/getdata/drawing/prenttree?entName="+name+"&type="+getDataType,
    type : "GET", 
    dataType:'json',
    async: false,
    success: function(req) {
    _loading.close();
    if(req.status == 200){
    var child = req.data;
    d.parents = child.parents;
            d._parents = null;
    }
    }
     });
      }
       
      }
 //刷新父节点
 that.updateParents(d); 
    },
    // 子节点画图   下画图
    toggleChild: function(d) {
    var name = d.name;
 var ind = name.indexOf("-");
 if(ind>0){
 name = name.substring(0,ind);
 }
 d.parents = null;
if (d.children) {
//收缩
       d._children = d.children;
       d.children = null;
      
     } else {
     if(d._children !=null){
     //上次是不是保存
     d.children = d._children;
       d._children = null;
     }else{
     _loading=new PublicLoading();
  _loading.open("正在加载,请稍后...");
     //查询一次子节点
     $.ajax({
  url:"/sistem/getdata/drawing/tree?entName="+name+"&type="+getDataType,
  type : "GET", 
  dataType:'json',
  async: false,
  success: function(req) {
  _loading.close();
  if(req.status == 200){
  var child = req.data;
  d.children = child.children;
       d._children = null;
  }
  }
     });
     }
     }
that.updateChildren(d);
    },
    //跟节点画图   上下画图
    toggle: function(d) {
        if (d.children) {
          d._children = d.children;
          d.children = null;
        } else {
          d.children = d._children;
          d._children = null;
        }
        if (d.parents) {
          d._parents = d.parents;
          d.parents = null;
        } else {
          d.parents = d._parents;
          d._parents = null;
        }
        that.updateBoth(d);
      },
      //子节点展开当前节点  收缩上次节点
    toggleCloseChild:function(d){
   
    },
    toggelCloseParent:function(d){
   
    },
    toggleAll: function(d) {
      if (d.children) {
        d.children.forEach(that.toggleAll);
        that.toggleChild(d);
      }
      if (d.parents) {
        d.parents.forEach(that.toggleAll);
        that.togglePrent(d);
      }
    }


  }


  return that;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!对于Vue和D3的组件开发,你可以使用Vue的生命周期钩子函数将D3与Vue组件集成起来。以下是一个简单的示例,展示如何使用Vue和D3创建一个treemap(树图)组件: 首先,安装必要的依赖: ```bash npm install d3 ``` 接下来,创建一个名为Treemap.vue的Vue组件,并在其中引入D3库: ```vue <template> <div ref="treemap"></div> </template> <script> import * as d3 from 'd3'; export default { mounted() { this.drawTreemap(); }, methods: { drawTreemap() { // 获取DOM元素的引用 const container = this.$refs.treemap; // 创建数据数组 const data = [ { name: 'A', value: 10 }, { name: 'B', value: 20 }, { name: 'C', value: 30 }, // ... ]; // 创建treemap布局 const treemapLayout = d3.treemap() .size([500, 300]) .padding(1); // 转换数据为适用于treemap的层次结构 const root = d3.hierarchy({ children: data }) .sum(d => d.value) .sort((a, b) => b.value - a.value); // 根据treemap布局计算节点位置和大小 treemapLayout(root); // 创建矩形元素并绑定数据 const rects = d3.select(container) .selectAll('rect') .data(root.leaves()); // 更新已存在的矩形 rects.attr('x', d => d.x0) .attr('y', d => d.y0) .attr('width', d => d.x1 - d.x0) .attr('height', d => d.y1 - d.y0) .attr('fill', 'steelblue'); // 创建新的矩形 rects.enter() .append('rect') .attr('x', d => d.x0) .attr('y', d => d.y0) .attr('width', d => d.x1 - d.x0) .attr('height', d => d.y1 - d.y0) .attr('fill', 'steelblue'); // 移除多余的矩形 rects.exit().remove(); } } } </script> ``` 以上代码演示了如何使用D3的treemap布局来创建一个简单的树图(treemap),你可以根据实际需求进行进一步的定制和样式调整。 希望这个示例能对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值