Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 v4 - Get current zoom scale?

In version 4 of D3.js, how do i get the current level of the zoom scale?

I want something like this:

var currentScale = zoom.scale();
like image 256
Matt Avatar asked Sep 01 '17 17:09

Matt


People also ask

How do you get the current zoom level in Diablo 3?

To retrieve the zoom state, use event. transform on a current zoom event within a zoom event listener (see zoom. on), or use d3. zoomTransform for a given node.

What does d3 zoom do?

D3 provides a module 'd3. zoom' that adds zoom and pan behaviour to an HTML or SVG element. This article shows how to create zoom behaviours, how to add zoom and pan constraints and how to zoom and pan programmatically.


1 Answers

There are two methods you could use.

One is to use d3.zoomTransform(element).k, see API documentation here. The element is the node of a selection rather than a d3 selection itself.

The other is to set a variable to keep track of the zoom scale and update it on every zoom event with k = d3.event.transform.k;. The intial value would normally be 1.

Both are used in this very slightly modified canonical zoom example from Mike Bostock: (scale factor displayed on zoom events and click events).

var canvas = d3.select("canvas"),
    context = canvas.node().getContext("2d"),
    width = canvas.property("width"),
    height = canvas.property("height"),
    radius = 2.5;

var points = d3.range(2000).map(phyllotaxis(10));

canvas.call(d3.zoom()
    .scaleExtent([1 / 2, 4])
    .on("zoom", zoomed))
    .on("click", displayScale);

drawPoints();


var k = 1;

function zoomed() {
  context.save();
  context.clearRect(0, 0, width, height);
  context.translate(d3.event.transform.x, d3.event.transform.y);
  context.scale(d3.event.transform.k, d3.event.transform.k);
  k = d3.event.transform.k;
  drawPoints();
  context.restore();
  
  // Method 1:
  console.log(d3.zoomTransform(canvas.node()).k);
   
  // Method 2:
  console.log(k);
}

function drawPoints() {
  context.beginPath();
  points.forEach(drawPoint);
  context.fill();
}

function drawPoint(point) {
  context.moveTo(point[0] + radius, point[1]);
  context.arc(point[0], point[1], radius, 0, 2 * Math.PI);
}

function phyllotaxis(radius) {
  var theta = Math.PI * (3 - Math.sqrt(5));
  return function(i) {
    var r = radius * Math.sqrt(i), a = theta * i;
    return [
      width / 2 + r * Math.cos(a),
      height / 2 + r * Math.sin(a)
    ];
  };
}

function displayScale() {
  // Method 1:
  console.log(d3.zoomTransform(canvas.node()).k);
   
  // Method 2:
  console.log(k);
}
<canvas width="960" height="500"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
like image 163
Andrew Reid Avatar answered Oct 31 '22 10:10

Andrew Reid