d3js: Use view port center for zooming focal point

前端 未结 3 609
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 01:53

We are trying to implement zoom buttons on top of a map created in D3 - essentially as it works on Google maps. The zoom event can be dispatched programmatically using

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 02:19

    A more succinct version of Wil's solution:

      var vis = d3.select('.vis');
      var zoom = d3.behavior.zoom()...
      var width = .., height = ..;
    
      function zoomByFactor(factor) {
        var scale = zoom.scale();
        var extent = zoom.scaleExtent();
        var newScale = scale * factor;
        if (extent[0] <= newScale && newScale <= extent[1]) {
          var t = zoom.translate();
          var c = [width / 2, height / 2];
          zoom
            .scale(newScale)
            .translate(
              [c[0] + (t[0] - c[0]) / scale * newScale, 
               c[1] + (t[1] - c[1]) / scale * newScale])
            .event(vis.transition().duration(350));
        }
      };
    
      function zoomIn() { zoomByFactor(1.2); }
      function zoomOut() { zoomByFactor(0.8); }
    

提交回复
热议问题