D3.js scaling mouse coordinates

I'm using the d3.js zoom feature to zoom in on the image inside the svg. I am using a mask to show the underlying image at the bottom. Unless I scale the mask and the coordinates of the mouse cursor match up perfectly. However, when I start to zoom in on the mouse coordinates, it does not move to the zoom level, so the map display no longer lines up with the cursor.

here is what i use so far ... i guess there must be some coordinate shift when scaling?

  var lightMap = d3.select("#lightMap").call(d3.behavior.zoom().scaleExtent([1, 3]).on("zoom", zoom));
var darkMap = d3.select("#darkMap").call(d3.behavior.zoom().scaleExtent([1, 3]).on("zoom", zoom));

function zoom() {
lightMap.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
darkMap.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");

var svg = d3.select("svg");

svg.on('mousemove', function () {

 var coordinates = [0, 0];
coordinates = d3.mouse(this);
var x = coordinates[0];
var y = coordinates[1];

    primaryCircle.setAttribute("cy", y + 'px');
    primaryCircle.setAttribute("cx", x + 'px');        




source to share

1 answer

(I know this is a late answer, but I had the same problem and thought I'd share how I fixed it for future people who see this)

Fix it . Use coordinates=mouse(lightMap.node())

/ darkMap.node()

instead mouse(this)

. Alternatively, and perhaps more correctly, call the zoom mode on svg

and keep using mouse(this)


Explanation . You are calling the mousemove function on svg

, so it mouse(this)

gets the coordinates in the element svg

. However, you are not applying the scaling behavior to svg

, which is why you end up with the wrong coordinates. Call mouse(_)

for the element that zooms in.



All Articles