Как остановить прыжки SVG при добавлении и уменьшении масштаба - PullRequest
1 голос
/ 19 марта 2020

привет, я только что добавил функцию масштабирования для дерева D3. js, но при перетаскивании svg он прыгает вверх и вниз, может кто-нибудь помочь мне с этим, и все работает, но только перетаскивание щипца svg не работает, и я пробовал мало Решения, приведенные в google добавления g, но проблема все еще не решена, может ли кто-нибудь помочь мне с этим?

Дерево D3. js Без увеличения

Дерево D3. js С увеличением

<!DOCTYPE html>
<meta charset="UTF-8">
<style>
.tooltip {  
    position: absolute;         
    text-align: left;           
      white-space: normal;                  
    padding: 4px;               
    font-size: 14px;        
    background: tan;    
    border: 1px solid gray;     
}

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}
.d3-context-menu {
    position: absolute;
    display: none;
    background-color: #f2f2f2;
    border-radius: 4px;

    font-family: Arial, sans-serif;
    font-size: 14px;
    min-width: 150px;
    border: 1px solid #d4d4d4;

    z-index:1200;
}

.d3-context-menu ul {
    list-style-type: none;
    margin: 4px 0px;
    padding: 0px;
    cursor: default;
}

.d3-context-menu ul li {
    padding: 4px 16px;
}

.d3-context-menu ul li:hover {
    background-color: #4677f8;
    color: #fefefe;
}
</style>

<body>
<div></div>
<!-- load the d3.js library --> 
<script src="https://d3js.org/d3.v4.min.js"></script>
<script >
function tooltip(){
return d3.select("body").append("div")  
    .attr("class", "tooltip")               
    .style("opacity", 0);}


d3.contextMenu = function (menu, openCallback) {

    // create the div element that will hold the context menu
    d3.selectAll('.d3-context-menu').data([1])
        .enter()
        .append('div')
        .attr('class', 'd3-context-menu');

    // close menu
    d3.select('div').on('click.d3-context-menu', function() {
        d3.select('.d3-context-menu').style('display', 'none');
    });

    // this gets executed when a contextmenu event occurs
    return function() { 
        let elm = this;

        d3.selectAll('.d3-context-menu').html('');
        let list = d3.selectAll('.d3-context-menu').append('ul');
        list.selectAll('li').data(menu).enter()
            .append('li')
            .html(function(d) {
                return d.title;
            })
            .on('click', function(d, i) {
                d.action(elm, data, index);
                d3.select('.d3-context-menu').style('display', 'none');
            });

        // the openCallback allows an action to fire before the menu is displayed
        // an example usage would be closing a tooltip
        if (openCallback) openCallback(data, index);

        // display context menu
        d3.select('.d3-context-menu')
            .style('left', (d3.event.pageX - 2) + 'px')
            .style('top', (d3.event.pageY - 2) + 'px')
            .style('display', 'block');

        d3.event.preventDefault();
    };
};</script>
<script>
var menu = [
            {
                title: 'URL',
                action: function(elm, d, i) {
                    console.log('Item #1 clicked!'+d);
                    console.log('The data for this circle is: ' + d);
                }
            },
            {
                title: 'ExPLORE',
                action: function(elm, d, i) {
                    console.log(d);
                    console.log('The data for this circle is: ' + d);
                }
            }
        ]

        var data = [1, 2, 3];
var selected=null;
var treeData =
  {
    "name": "Top Level",
    "children": [
      { 
        "name": "Level 2: A",
        "children": [
          { "name": "Son of A" },
          { "name": "Daughter of A" }
        ]
      },
      { "name": "Level 2: B" }
    ]
  };
//Predefined Box Size 
  let rectNode = {
  width: 120,
  height: 17,
  textMargin: 5
  };
// Set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("div")

.append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom);

  svg.call(d3.zoom().on("zoom", function () { svg.attr("transform", d3.event.transform) }));
svg.append("g")
    .attr("transform", "translate("
          + margin.left + "," + margin.top + ")")
  ;
var i = 0,
    duration = 750,
    root;

// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);

// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;

// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if(d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {

  // Assigns the x and y position for the nodes
  var treeData = treemap(root);

  // Compute the new tree layout.
  var nodes = treeData.descendants(),
      links = treeData.descendants().slice(1);

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

  // ****************** Nodes section ***************************

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

  // Enter any new modes 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);

  // Add Circle for the nodes
  nodeEnter.append('circle')
      .attr('class', 'node')
      .attr('r', 0)
      .style("fill", function(d) {
          return d._children ? "lightsteelblue" : "#fff";
      });
let rectGrpEnter = nodeEnter.append('g')
  .attr('class', 'node-rect-text-grp');
  rectGrpEnter.append('rect')
  .attr('rx', 6)
  .attr('ry', 6)
  .attr('x',-20)
  .attr('y',-20)
  .style('fill', "#337ab7")
  .attr('width',  50)
  .attr('height',50)
  .on('contextmenu', d3.contextMenu(menu));
  // Add labels for the nodes
  nodeEnter.append('text')
      .attr("dy", ".35em")
      .attr("x", function(d) {
          return d.children || d._children ? -13 : 13;
      })
      .attr("text-anchor", function(d) {
          return d.children || d._children ? "end" : "start";
      })
      .text(function(d) { return d.data.name; });

  // UPDATE
  var nodeUpdate = nodeEnter.merge(node);

  // Transition to the proper position for the node
  nodeUpdate.transition()
    .duration(duration)
    .attr("transform", function(d) { 
        return "translate(" + d.y + "," + d.x + ")";
     });

  // Update the node attributes and style
  nodeUpdate.select('circle.node')
    .attr('r', 10)
    .style("fill", function(d) {
        return d._children ? "lightsteelblue" : "#fff";
    })

    .attr('cursor', 'pointer');


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

  // On exit reduce the node circles size to 0
  nodeExit.select('circle')
    .attr('r', 1e-6);

  // On exit reduce the opacity of text labels
  nodeExit.select('text')
    .style('fill-opacity', 1e-6);

  // ****************** links section ***************************

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

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

  // UPDATE
  var linkUpdate = linkEnter.merge(link);

  // Transition back to the parent element position
  linkUpdate.transition()
      .duration(duration)
      .attr('d', function(d){ return diagonal(d, d.parent) });

  // Remove any exiting links
  var linkExit = link.exit().transition()
      .duration(duration)
      .attr('d', function(d) {
        var o = {x: source.x, y: source.y}
        return diagonal(o, o)
      })
      .remove();

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

  // Creates a curved (diagonal) path from parent to the child nodes
  function diagonal(s, d) {

    path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`

    return path
  }

  // 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);
  }

  function contextmenu(d){
  if(d.children){
  alert("Has Children")
  }
  else{
  alert("NO Has Children")
  selected = d;
   update(d);


   var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars":[  {name: "child1"}, { name: "child2"},  {name: "child3"}]
};

for (i in myObj.cars) {
   var newNodeObj =myObj.cars[i];
   ;
   //Creates new Node
   var newNode = d3.hierarchy(newNodeObj);
   newNode.depth = selected.depth + 1;
   newNode.height = selected.height - 1;
   newNode.parent = selected;

   if(!selected.children){
     selected.children = [];
         selected.data.children = [];
   }
   selected.children.push(newNode);
  }
  update(selected);
  }
  }
}

</script>
</body>


...