【问题标题】:Recognize point(x,y) is inside svg path or outside识别点(x,y)在 svg 路径内部或外部
【发布时间】:2014-01-14 07:58:08
【问题描述】:

我已关闭 SVG 路径,即该国的省份。

如何通过javascript识别点(x,y)是在SVG路径内部还是在外部?

【问题讨论】:

标签: javascript svg


【解决方案1】:

致电document.elementFromPoint。如果位置在路径中,那么它将返回该元素。如果路径未填充,则可能需要调整 pointer-events 属性使其正常工作。

【讨论】:

  • 这在 IE 和 Edge 中都不起作用。它只会返回整个 SVG。
  • @Hack5 你需要使用掩码在元素上调用它,而不是掩码。
【解决方案2】:

对于SVGGeometryElement,包括路径和基本形状,有

正如名字所暗示的,它们返回给定点是否在笔划中各自的填充中。

例子:

const svg = document.getElementById("your-svg");
const path = document.getElementById("your-path");

// SVGPoint is deprecated according to MDN
let point = svg.createSVGPoint();
point.x = 40;
point.y = 32;

// or according to MDN
// let point = new DOMPoint(40, 32);

console.log("In stroke:", path.isPointInStroke(point)); // shows true
console.log("In fill:", path.isPointInFill(point)); // shows false
<svg id="your-svg" width="200" height="200">
  <path d="M 10 80 C 40 10, 65 10, 95 80 S 150 10, 150 110 S 80 190, 40 140 Z" stroke="yellowgreen" stroke-width="5" fill="#adff2f77" id="your-path"/>
  
  <!-- only to show where the point is -->
  <circle id="stroke-point" cx="40" cy="32" r="2.5" fill="red" />
</svg>

除了比Document.elementFromPoint() 更具描述性之外,这些函数可以正确处理堆叠元素和指针事件。请注意,上面的示例已经包含放置在请求点的路径上的小圆圈。用Document.elementFromPoint() 来检查这种情况是不可能或几乎不可能的。

const svg = document.getElementById("your-svg");
const path = document.getElementById("your-path");

console.log("In stroke / fill:", svg.ownerDocument.elementFromPoint(40, 32) == path);
<svg id="your-svg" width="200" height="200">
  <path d="M 10 80 C 40 10, 65 10, 95 80 S 150 10, 150 110 S 80 190, 40 140 Z" stroke="yellowgreen" stroke-width="5" fill="#adff2f77" id="your-path"/>
  
  <!-- only to show where the point is -->
  <circle id="stroke-point" cx="40" cy="32" r="2.5" fill="red" />
</svg>

编辑:感谢@Arlo 指出要使用的点表示对象不清楚。 MDN 使用DOMPoint(或DOMPointInit)。 Chrome 假定会得到一个 SVGPoint,根据 MDN 已弃用。

请注意,目前尚不清楚对 Edge 和1 Internet Explorer 的支持(根据 MDN)。


1根据 MDN Edge ≥79 同时支持isPointInStroke()isPointInFill()

【讨论】:

  • Uncaught TypeError: Failed to execute 'isPointInFill' on 'SVGGeometryElement': parameter 1 is not of type 'SVGPoint'. 似乎 Chrome 期待的不是 MSDN 所说的。
  • @Arlo 感谢您指出这一点。我更改了答案,现在应该可以在 Chrome 中使用(未经测试,我不使用 Chrome)。
猜你喜欢
  • 1970-01-01
  • 2013-05-30
  • 2021-01-08
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
相关资源
最近更新 更多