s_dev
s_dev

Reputation: 255

d3.js zooming mouse coordinates

Im using d3.js zoom function to zoom in on an image inside an svg. Im using a mask to reveal an underlying image beneath. If i dont zoom the mask and mouse cursor coordinates match up perfectly. However, when i start to zoom the mouse coordinates are not translating to the zoom level, thus the map reveal is not lining up with the cursor anymore.

here is what im using so far...Im assuming there needs to be some sort of coordinate translation when zooming?

  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');        

});

Upvotes: 5

Views: 3029

Answers (1)

RatherBeLunar
RatherBeLunar

Reputation: 43

(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: Use coordinates=mouse(lightMap.node()) / darkMap.node() instead of mouse(this). Alternatively, and probably more correctly, call the zoom behavior on svg and keep using mouse(this).

Explanation: You call the mousemove function on svg, so mouse(this) gets the coordinates within the svg element. However you don't apply the zoom behavior to svg, so you get wrong coordinates. Call mouse(_) on an element that zooms.

Upvotes: 4

Related Questions