How to get the click coordinates relative to SVG element holding the onclick listener?

前端 未结 3 1014
萌比男神i
萌比男神i 2020-12-25 11:37

I haven\'t been able to calculate the click coordinates (x and y) relative to the element triggering the event. I have not found an easy example online.

I have a sim

3条回答
  •  眼角桃花
    2020-12-25 12:12

    Adding notes after many researchs (and fails!).

    For a css translated svg, to get the coordinates of a clicked point for drawing.

    In my case, using a mouse wheel event to translateX, so the actual rendering depends of the screen size and of the actual translated value.

    I recommend for your use case to make a little drawing like the following, it will help a lot for figuring out what's going on.

    Let's say my svg has for id: shoke To get the total computed width, in pixels:

    shoke.getBoundingClientRect()["width"]
    

    Need to know the actual translateX value. (From the right, so it is a negative number, on this case)

    shoke.style.transform.substr(11).slice(0,-3)
    

    Note that it return a string and not an integer, so:

    +shoke.style.transform.substr(11).slice(0,-3)
    

    Now to get the coordinates of the mouse, related to the pixel x0 of the screen.

    let pt = document.querySelector('svg').createSVGPoint();
    pt.matrixTransform(shoke.getScreenCTM().inverse())["x"]
    

    So, at the end, to obtain the precise x point:

    svg_width - (svg_width + translated) + from_pixel x0 of the screen_click
    

    Is something like this:

    shoke.getBoundingClientRect()["width"]  - (shoke.getBoundingClientRect()["width"] + +shoke.style.transform.substr(11).slice(0,-3)) + pt.matrixTransform(shoke.getScreenCTM().inverse())["x"]
    

提交回复
热议问题