Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

javascript - 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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...