Getting the SVG coordinates of a click event
If you need to translate mouse coordinates to svg coordinates, instead of using the deprecated createSvgPoint
function, you can use a DomPoint
. It's not the top-most answer in StackOverflow when searching for this issue, so
it might evade your eyes the first time.
Here's the code:
Using the svg element's current matrix transform (along with e.clientX, e.clientY
) ensures that no matter the viewbox, or how you scroll, move, scale or rotate, the coordinates
match perfectly to the click position.
Example
Here's an example with a scaled, translated and rotated SVG element (and some animations using
Svelte).
Try clicking inside the rectangle.
x: 0, y: 0 (viewbox="0 0 200 100")