简体   繁体   中英

D3 v4 - Detect click coordinates in zoomed area

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: https://bl.ocks.org/anonymous/3e3e5333ff24a2c9972bc9320dc6f712/f4dcd09a07b5eafdc78efa0cf45948021e003739

Solution provided by Gerardo Furtado

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM