【发布时间】:2014-01-14 07:58:08
【问题描述】:
我已关闭 SVG 路径,即该国的省份。
如何通过javascript识别点(x,y)是在SVG路径内部还是在外部?
【问题讨论】:
-
你可以试试看这个问题stackoverflow.com/questions/10525729/…
-
我不能使用 raphael 或其他库。
标签: javascript svg
我已关闭 SVG 路径,即该国的省份。
如何通过javascript识别点(x,y)是在SVG路径内部还是在外部?
【问题讨论】:
标签: javascript svg
致电document.elementFromPoint。如果位置在路径中,那么它将返回该元素。如果路径未填充,则可能需要调整 pointer-events 属性使其正常工作。
【讨论】:
对于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 所说的。