Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 click coordinates after pan and zoom

I'm using D3 library to create drawing application.

I need to draw object (circle for simplicity) on the coordinates where user clicked. Problem is when user uses the pan & zoom and moves the viewport. Then object is places on wrong position (I guess the problem is event coordinates are relative to svg element and not g, so they are calculated without proper transformation).

$('svg').on('click', function(event) {
    d3.select('#content-layer').append('circle')
    .attr('r', 10)
    .attr('cx', event.offsetX)
    .attr('cy', event.offsetY)
    .attr('stroke', 'black')
    .attr('fill', 'white');
});

var zoomBehavior = d3.behavior.zoom()
    .scaleExtent([1, 10])
  .on('zoom', () => {
    var translate = "translate(" + d3.event.translate + ")";
    var scale = "scale(" + d3.event.scale + ")";
    d3.select('#content-layer').attr("transform", translate + scale);
    });

d3.select('svg').call(zoomBehavior);

I tried to add on click callback to g element, but it is not working (I guess it doesn't have any size?).

Here is jsfiddle: https://jsfiddle.net/klinki/53ftaw7r/

like image 707
Klinki Avatar asked Mar 17 '16 08:03

Klinki


1 Answers

Basically you need to take care of the translate when you click.

So I created a variable :

var translateVar = [0,0];

When you pan update this variable :

translateVar[0] = d3.event.translate[0];
translateVar[1] = d3.event.translate[1];

And add this to your coordinates of the circle :

.attr('cx', mouseCoords[0] - translateVar[0] )
.attr('cy', mouseCoords[1] - translateVar[1])

Updated fiddle : https://jsfiddle.net/thatoneguy/53ftaw7r/2/

You also need to take care of the scale so do a similar thing :

var scaleVar = 1;

Update variable on zoom :

scaleVar = d3.event.scale

New coordinates :

.attr('cx', (mouseCoords[0] - translateVar[0]) /scaleVar )
.attr('cy', (mouseCoords[1] - translateVar[1]) /scaleVar )

Final fiddle : https://jsfiddle.net/thatoneguy/53ftaw7r/5/

like image 94
thatOneGuy Avatar answered Oct 19 '22 19:10

thatOneGuy