I need to convert from a javascript click event to the coordinate space of an SVG element. I am currently using techniques like https://stackoverflow.com/a/48354404/995935 , but https://developer.mozilla.org/en-US/docs/Web/API/SVGPoint says that SVGpoint is "no longer recommended" and "may cease to work at any time".
Unfortunately, it does not mention what API should be used to replace it.
How should I rewrite the code sample
function screenToSVG(screenX, screenY) {
var p = svg.createSVGPoint()
p.x = screenX
p.y = screenY
return p.matrixTransform(svg.getScreenCTM().inverse());
}
to avoid deprecated APIs?
Using DOMPoint(). I was searching for this myself and it looks like it can replace SVGPoint 1:1. Here is an example:
const svg = document.getElementById('svg01');
const print = document.getElementById('print');
const toSVGPoint = (svg, x, y) => {
let p = new DOMPoint(x, y);
return p.matrixTransform(svg.getScreenCTM().inverse());
};
svg.addEventListener('click', e => {
let p = toSVGPoint(e.target, e.clientX, e.clientY);
print.textContent = `x: ${p.x} - y: ${p.y}`;
});
svg {
border: thin solid black;
cursor: pointer;
}
<p id="print">Position</p>
<svg id="svg01" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 500" width="400">
<text font-size="100" x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" pointer-event="none">Click me...</text>
</svg>