我有一个问题,与chrome版本的SVGGeometryElement.isPointInFill()(在Firefox中工作)

xnifntxz  于 2023-03-10  发布在  Go
关注(0)|答案(1)|浏览(117)

https://jsfiddle.net/awebnoyz/
如果一个点在这个区域内,我需要每秒检查几千条路径。path.isPointInFill(point)在firefox中可以实现这个功能,而chrome返回false。
我只想在不画任何东西的情况下进行检查,但是chrome似乎只有在元素实际添加到文档中时才起作用,如果添加路径,则需要大约100倍的时间。
有什么建议吗?

const sPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
sPath.setAttribute('d', "M0 0 L10 0 L10 10 L0 10 Z");
const sPoint = document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGPoint();
sPoint.x = 5;
sPoint.y = 5;

console.log("virtual:" + sPath.isPointInFill(sPoint));
//chrome:false, firefox:true

//now with actually adding an svg and the path to the document, both return true
svg = document.documentElement.appendChild(document.createElementNS("http://www.w3.org/2000/svg", "svg"))
svg.appendChild(sPath);
console.log("appended:" + sPath.isPointInFill(sPoint));
svg.removeChild(sPath);

我目前没有主意了,改用光线投射,这“只”需要10倍的时间:)

2jcobegt

2jcobegt1#

Chrome确实支持通过CSS设置d属性,因此,对于不在DOM中的元素(因此无法计算所有CSS规则),Chrome不支持此方法是有道理的。
根据需要,可以将Path2D(svgString)构造函数与画布2D isPointInPath()方法沿着使用:

const ctx = document.createElement("canvas").getContext("2d");
const path = new Path2D("M0 0 L10 0 L10 10 L0 10 Z");
const pt = { x: 5, y: 5 }
console.log(ctx.isPointInPath(path, pt.x, pt.y));

相关问题