Accepted answer


The d3 zoom behavior does not track or know about what transforms you've applied to an element. It is initialized with scale equal to 1 and translate equal to 0,0. So, when you use

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

in your zoomed function, you are zooming relative to this initial scale and translate.


Not every d3 zoom manipulates the transform of the SVG element it is called on: you may want to have zoom interaction everywhere on a plot, but only zoom the plot area and not the margins. Many d3 zooms don't manipulate any SVG transform: they may use semantic zooming, or the zoom may be altering a canvas rather than SVG, etc. As such, a d3-zoom behavior is independent of any SVG transorm attribute on the element(s) it is called on.


If your zooming by manipulating the transform attribute of an SVG element, let D3 zoom do all of the manipulation - no need to manipulate it manually and have a zoom, this is how the zoom gets out of step.


You can programmatically trigger a zoom event prior to rendering anything. The easiest way to do so is to use:, d3.zoomIdentity.translate(x,y).scale(k));

This line triggers a zoom event. We can use this prior to rendering anything and rely on the zoomed function to set the initial value of the SVG transform attribute. All subsequent zooms will be relative to this and we can proceed as normal:

var svg ="svg");

var g = svg.append("g"); 
// define a zoom behavior:
var zoom = d3.zoom()
  .on("zoom", zoomed);
// call the zoom:

// trigger tha initial zoom with an initial transform.,d3.zoomIdentity.scale(20).translate(-100,-100));

// draw the visualization:
var rect = g.append("rect")
  .attr("width", 5)
  .attr("height", 5)
  .attr("x", 100)
  .attr("y", 100);
// zoomed function:
// zoom as normal.
function zoomed() {
<script src=""></script>
<svg width="500" height="300"></svg>

The above snippet applies an initial zoom (scale 20, translate -100,-100) and uses this as the starting point for the zoom interaction. The comment should help explain the process.


// It appears that you're moving #mainGrid and not #svg. So when you call zoom from svgElement it is zooming from it's 0,0 position. 

// Or it may because you don't have pound sign in
var svgElement ="#svg");

// Try changing svgElement to gridElement
  .scaleExtent([1 / 2, 4])
  .on("zoom", zoomed));

Related Query

More Query from same tag