D3 v4 - zoom with buttons in conflict with the zoom mode

I created a gist with my problem.

I started with this example .

So my problem is that I need zoom in and out buttons in addition to the mouse controls.

Mouse controls (zooming with the wheel and panning by dragging and dropping) are implemented using the zoom () action . It works very well.

Then I added two buttons to zoom in and out:

var _zoom = d3.zoom()
    .scaleExtent([1 / 2, 8])
    .on("zoom", zoomed);
var gui = d3.select("#gui")
gui.append("span")
  .classed("zoom in", true)
  .text("+")
  .on("click", function() { _zoom.scaleBy(container, 2); })
gui.append("span")
  .classed("zoom out", true)
  .text("-")
  .on("click", function(){ _zoom.scaleBy(container, 0.5); })

. , ( ), +: .

?

+4
1

, node, _zoom.

svg node,

svg.call(_zoom);

svg, svg node g node,

g.attr("transform", d3.event.transform);

, g , - , svg node,

 _zoom.scaleBy(svg, 0.5);

svg node, ,

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");
svg.style("border", "solid 1px black");
var points = d3.range(2000).map(phyllotaxis(10));
var g = svg.append("g");

var _zoom = d3.zoom()
  .scaleExtent([1 / 2, 8])
  .on("zoom", function() {
    g.attr("transform", d3.event.transform);
  });
svg.call(_zoom);

var container = 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)

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)
    };
  };
}
var gui = d3.select("#gui");
gui.append("span")
  .classed("zoom in", true)
  .text("+")
  .on("click", function() {
    _zoom.scaleBy(svg, 2);
  });
gui.append("span")
  .classed("zoom out", true)
  .text("-")
  .on("click", function() {
    _zoom.scaleBy(svg, 0.5);
  })
<svg width="960" height="500"></svg>
<div id="gui"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
Hide result
+10

Source: https://habr.com/ru/post/1658848/


All Articles