最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

svg - What is the replacement for the deprecated SVGPoint javascript API? - Stack Overflow

programmeradmin1浏览0评论

I need to convert from a javascript click event to the coordinate space of an SVG element. I am currently using techniques like , but says that SVGpoint is "no longer remended" 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?

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./a/48354404/995935 , but https://developer.mozilla/en-US/docs/Web/API/SVGPoint says that SVGpoint is "no longer remended" 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?

Share Improve this question asked Nov 10, 2021 at 16:11 Mutant BobMutant Bob 3,6183 gold badges33 silver badges59 bronze badges 2
  • 1 developer.mozilla/en-US/docs/Web/API/DOMPoint, although SVGPoint is somewhat less deprecated than it used to be. DOMPoint works in Firefox, not sure about other UAs – Robert Longson Commented Nov 10, 2021 at 16:18
  • 1 There is so much code out there on the web that uses SVGPoint. I wouldn't worry about it disappearing anytime soon. It'll be around for years yet. – Paul LeBeau Commented Nov 11, 2021 at 8:59
Add a ment  | 

1 Answer 1

Reset to default 9

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/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>

发布评论

评论列表(0)

  1. 暂无评论