d3.js pan and zoom jumps when using mouse after programatic zoom

后端 未结 1 1617
醉话见心
醉话见心 2020-12-21 05:16

I\'m trying to center my d3 graph when it loads. So I run

var g = svg.append(\"g\");

//... then later

g.call(zoom.transform, center);

It

1条回答
  •  -上瘾入骨i
    2020-12-21 06:07

    You are applying your event on a different object (the g) then what the zoom is set up on (the svg). Since the zoom event is referenced against the element it is applied to, d3 does not now about your initial centering. From the docs:

    The zoom behavior stores the zoom state on the element to which the zoom behavior was applied, not on the zoom behavior itself. This is because the zoom behavior can be applied to many elements simultaneously, and each element can be zoomed independently. The zoom state can change either on user interaction or programmatically via zoom.transform.

    Changing your call to svg.call(zoom.transform, center); fixes your issue.

    Complete code:

    var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height"),
        transform = d3.zoomIdentity;
    
    var points = d3.range(2000).map(phyllotaxis(10));
    
    var zoom = d3.zoom()
        .scaleExtent([1 / 2, 8])
        .on("zoom", zoomed);
    
    var g = svg.append("g");
    
    g.selectAll("circle")
        .data(points)
      .enter().append("circle")
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", 2.5)
        .call(d3.drag()
            .on("drag", dragged));
    
    svg.call(zoom);
    
    function zoomed() {
      g.attr("transform", d3.event.transform);
    }
    
    function center() {
      return d3.zoomIdentity
            .scale(0.5);
    }
    
    function dragged(d) {
      d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
    }
    
    function phyllotaxis(radius) {
      var theta = Math.PI * (3 - Math.sqrt(5));
      return function(i) {
        var r = radius * Math.sqrt(i), a = theta * i;
        return {
          x: width / 2 + r * Math.cos(a),
          y: height / 2 + r * Math.sin(a)
        };
      };
    }
    
    svg.call(zoom.transform, center);
    
    
    
      
      
      JS Bin
    
    
    
    
    
    

    0 讨论(0)
提交回复
热议问题