Accepted answer

in order to convert the coordinate returned by d3.mouse to the coordinate system used by d3.zoom, you need to get the zoom transform in addition to the coordinates returned by d3.mouse. i'll highlight one method here.

you can get the current zoom transform with:


where selection is the d3 selection the zoom is called on. while d3.mouse() gives us the screen coordinates of the mouse relative to the container, we can use that and the transform to give us the scaled and translated coordinates with transform.invert(), which takes a point and will return the zoomed coordinates:

  var xy = d3.mouse(this);         // relative to specified container
  var transform = d3.zoomtransform(selection.node());
  var xy1 = transform.invert(xy);  // relative to zoom

here's a quick example showing extraction of the zoomed coordinates as compared with the mouse coordinates. the axes are just to give a rough idea of what the zoom coordinate system is (they show zoom coordinates), but the functionality remains the same without them:

var svg ="body")
  .attr("width", 500)
  .attr("height", 300)
var g = svg.append("g")
var rect = g.append("rect")

var x = d3.scalelinear().domain([0,400]).range([0,400]);
var y = d3.scalelinear().domain([0,200]).range([0,200]);

var axisx = d3.axistop().scale(x).ticksize(-200)
var axisy = d3.axisleft().scale(y).ticksize(-400);

var gx = g.append("g").call(axisx)
var gy = g.append("g").call(axisy)

var zoom = d3.zoom()
  .scaleextent([1, 8])

rect.on("click", function() {
  var xy = d3.mouse(this);
  var transform = d3.zoomtransform(rect.node());
  var xy1 = transform.invert(xy);

  console.log("mouse:[", xy[0], xy[1], "] zoomed:[",xy1[0],xy1[1],"]")
function zoomed() {;;
rect {
  cursor: pointer;
.tick line {
  stroke: #ccc;
  pointer-events: none;
<script src=""></script>

of course you must ensure that d3.mouse and d3.zoom are referencing the same thing, in this case the rectangle.

Related Query

More Query from same tag