D3 click coordinates after pan and zoom

前端 未结 1 357
一生所求
一生所求 2020-12-20 23:46

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 t

相关标签:
1条回答
  • 2020-12-21 00:33

    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/

    0 讨论(0)
提交回复
热议问题