我需要从 javascript 单击事件转换为 SVG 元素的坐标空间。我目前正在使用/sf/answers/3384808311/等技术,但是https://developer.mozilla.org/en-US/docs/Web/API/SVGPoint表示 SVGpoint “不再推荐” ”和“可能随时停止工作”。
不幸的是,它没有提到应该用什么API来代替它。
我应该如何重写代码示例
function screenToSVG(screenX, screenY) {
var p = svg.createSVGPoint()
p.x = screenX
p.y = screenY
return p.matrixTransform(svg.getScreenCTM().inverse());
}
Run Code Online (Sandbox Code Playgroud)
避免使用已弃用的 API?
使用DOMPoint()。我自己正在寻找这个,看起来它可以替代 SVGPoint 1:1。这是一个例子:
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}`;
});Run Code Online (Sandbox Code Playgroud)
svg {
border: thin solid black;
cursor: pointer;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)