D3.js: increment on click event

I tried to achieve the same behavior by Wil Linssen's implementation but on d3.js version 4. I'm pretty confused about the api scaling in version 4.

Changes I made to the original implementation: zoom.translate()

replace with   d3.zoomTransform(selection.node())

and add the appropriate dots instead:

svg.attr("transform",
    "translate(" + t.x + "," + t.y + ")" +
    "scale(" + t.k + ")"
);

      

This:

zoom
  .scale(iScale(t))
  .translate(iTranslate(t));

      

replaced by

var foo = iTranslate(t);
zoom.
  translateBy(selection, foo[0], foo[1]);
zoom
  .scaleBy(selection, iScale(t));

      

But it still has a problem, it looks like a scale, decreasing ...

Example: Example on d3.v4 - jsfiddle

thanks for the help

+3


source to share


2 answers


By exploring the easiest way to use the d3 v4 api that provides interpolation, etc. from the box. In the original interrogative meaning implemented from scratch, this doesn't make sense in version 4. The solution is similar to @ Nixie's answers and has a few lines of code.

This version includes panning, if you don't need it, remove svg.call(zoom);

Final example: Zoom D3 v4 - jsfiddle

One interesting note: Function:



function transition() {
  svg.transition()
      .delay(100)
      .duration(700)
      .call(zoom.scaleTo, zoomLevel);
      //.on("end", function() { canvas.call(transition); });
}

      

call(zoom.ScaleTo, zoomLevel)

- will zoom in to the center of the page. But if you want the center of the image, use it:call(zoom.transform, transform);

Where transform

is the function that sets the center of your image. For example, a function like this:

function transform() {
  return d3.zoomIdentity
      .translate(width / 2.75, height / 2.75)
      .scale(zoomLevel)
      .translate(-width/2.75, -height/2.75);
}

      

+2


source


This piece of code doesn't solve all problems, but it can be a starting point. In D3 v4 you can convert the scale in one line of code (see also https://github.com/d3/d3-zoom/blob/master/README.md#zoom_transform )

function interpolateZoom (translate, scale) {
    return selection.transition().duration(350)
              .call(zoom.transform, 
                    d3.zoomIdentity.translate(translate[0], translate[1]).scale(scale))
}

      



Modified example: https://jsfiddle.net/2yx1cLrq/ . Also, you need to replace selection

with selection.node()

in all callsd3.zoomTransform

+2


source







All Articles