score:6

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:

``````d3.zoomtransform(selection.node());
``````

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 = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 300)
.attr("fill","#eee");

var g = svg.append("g")
.attr("transform","translate(50,50)");

var rect = g.append("rect")
.attr("width",400)
.attr("height",200)
.attr("fill","#eee");

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])
.on("zoom",zoomed);

rect.call(zoom);

rect.on("click", function() {
var xy = d3.mouse(this);

var transform = d3.zoomtransform(rect.node());
var xy1 = transform.invert(xy);

console.log("mouse:[", xy, xy, "] zoomed:[",xy1,xy1,"]")
})

function zoomed() {
gx.call(axisx.scale(d3.event.transform.rescalex(x)));
gy.call(axisy.scale(d3.event.transform.rescaley(y)));
}``````
``````rect {
cursor: pointer;
}
.tick line {
stroke: #ccc;
pointer-events: none;
}``````
``<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>``

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