【问题标题】:What is the replacement for the deprecated SVGPoint javascript API?什么是已弃用的 SVGPoint javascript API 的替代品?
【发布时间】:2021-12-23 05:57:12
【问题描述】:

我需要将 javascript 点击事件转换为 SVG 元素的坐标空间。我目前正在使用 https://stackoverflow.com/a/48354404/995935 之类的技术,但 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());
}

避免使用已弃用的 API?

【问题讨论】:

  • developer.mozilla.org/en-US/docs/Web/API/DOMPoint,尽管 SVGPoint 的弃用程度不如以前。 DOMPoint 在 Firefox 中工作,不确定其他 UA
  • 网络上有很多使用 SVGPoint 的代码。我不会担心它很快就会消失。它会存在很多年。

标签: javascript svg


【解决方案1】:

使用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}`;
});
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>

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多