chipnot
chipnot

Reputation: 79

remove/unbind d3 zoom from canvas

Is there any way to completely remove/unbind the d3.zoom from canvas? I wanted to enable only the zoom functionality when the zoom is enabled (via separate button setting) and reclaim the mouse events (mouse down, up etc) when it is removed.

here is how I add the d3 zoom to canvas

///zoom-start
var d3Zoom = d3.zoom().scaleExtent([1, 10]).on("zoom", zoom),
    d3Canvas  = d3.select("canvas").call(d3Zoom).on("dblclick.zoom", null),
    d3Ctx     = d3Canvas.node().getContext("2d"),
    d3width   = d3Canvas.property("width"),
    d3height  = d3Canvas.property("height");

function zoom() {
}

Any help would be appreciated. Thanks in advance

Upvotes: 2

Views: 737

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

According to the API:

Internally, the zoom behavior uses selection.on to bind the necessary event listeners for zooming. The listeners use the name .zoom, so you can subsequently unbind the zoom behavior as follows:

selection.on(".zoom", null);

And, to enable it again, you just need:

selection.call(zoom);

Here is a demo (the buttons are self explanatory):

var svg = d3.select("svg");
var g = svg.append("g");
var zoom = d3.zoom().on("zoom", function() {
  g.attr("transform", d3.event.transform)
});
svg.call(zoom);

g.append("circle")
  .attr("cx", 150)
  .attr("cy", 75)
  .attr("r", 50)
  .style("fill", "teal");

d3.select("#zoom").on("click", function() {
  svg.call(zoom);
  console.log("zoom enabled")
});

d3.select("#nozoom").on("click", function() {
  svg.on(".zoom", null)
  console.log("zoom disabled")
});
svg {
  border: 1px solid gray;
}

.as-console-wrapper { max-height: 9% !important;}
<script src="https://d3js.org/d3.v4.min.js"></script>
<button id="zoom">Enable zoom</button>
<button id="nozoom">Disable zoom</button>
<br>
<svg></svg>

PS: I'm using SVG, not canvas, but the principle is the same.

Upvotes: 3

Related Questions