Reputation: 1455
I am going to build some kind of ui to manage dependencies between blocks with d3 version 4.
I need to add new element onClick - it works fine, but if container element is zoomed in/out - coordinates of click are wrong, of course.
There should be well defined approach to do that, but I cannot find example for version 4 of d3 library. Will appreciate any help.
Illustration of problem: https://bl.ocks.org/bfunc/e8c5649f1a3233b4141b36f6ffdff79c
Edited:
Solution provided by Gerardo Furtado
Upvotes: 4
Views: 649
Reputation: 102174
In order to track all the zoom and panning, you can create an object...
let zoomTrans = {x:0, y:0, scale:1};
... which you update in the zoom function:
zoomTrans.x = d3.event.transform.x;
zoomTrans.y = d3.event.transform.y;
zoomTrans.scale = d3.event.transform.k;
Then, in the click function, use this math:
let x = (d3.event.x - zoomTrans.x)/zoomTrans.scale;
let y = (d3.event.y - zoomTrans.y)/zoomTrans.scale;
Here is the updated bl.ocks: https://bl.ocks.org/anonymous/3e3e5333ff24a2c9972bc9320dc6f712/f4dcd09a07b5eafdc78efa0cf45948021e003739
Upvotes: 3