识别点(x,y)在svg路径内或外部

Pee*_*yte 2 javascript svg

我关闭了SVG路径,这是该国的省份.

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

Rob*_*son 5

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


mii*_*le7 5

对于SVGGeometryElement其中包括路径和基本形状,有SVGGeometryElement.isPointInStroke()SVGGeometryElement.isPointInFill()方法。它们返回给定的点是在笔画中还是在填充中。

例子:

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
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

请注意,支持 边和1 Internet Explorer 目前未知(根据 MDN)。


1根据 MDN Edge ?79 支持,isPointInStroke()isPointInFill()