使用getBoundingClientRect仅查找SVG特定区域中的元素

3

我正在使用 python svgwrite 创建一个 SVG 文件,在我的绘图中心有一个由路径创建的形状。我想要删除不在我的包裹形状内的元素。

首先,我能否在 svgwrite 中删除它们?如果不能,我该如何使用 JavaScript 查找所有元素,并删除不在我的形状内的任何一个元素?

svgwrite

# dots that are genrated in the svg are like this
image.add(image.circle((x, y), mag, id='dot', stroke="none", fill=color))

# this is my heart shape that should dots go inside of it
image.defs.add(image.path(d="M0 200 v-200 h200 a100,100 90 0,1 0,200 a100,100 90 0,1 -200,0z", id="heart_shape", style="rotate: 225deg;scale:1.9;stroke: #fff;", opacity="1"))
image.add(image.use(href="#heart_shape", fill="none", insert=(half_x, str(height-80)+"mm"), id="heart_wrapper"))

我喜欢使用JavaScript在前端删除它们。我可以像下面这样获取形状的绑定框:

var heart = document.querySelector("#heart_wrapper")
var {xHeart, yHeart} = heart.getBBox()
注意:我不确定如何确定一个是否在我的形状内。 我知道如何选择所有的点并将它们移除。

这是生成的 SVG 形状:

<use xmlns="http://www.w3.org/2000/svg" fill="none" id="heart_wrapper" x="377.9527559055118" xlink:href="#heart_shape" xmlns:xlink="http://www.w3.org/1999/xlink" y="195mm">
<path d="M0 200 v-200 h200 a100,100 90 0,1 0,200 a100,100 90 0,1 -200,0z" id="heart_shape" opacity="1" style="rotate: 225deg;scale:1.9;stroke: #fff;"></path>
</use>

1
顺便说一下,我发现element.getBoundingClientRect()方法将返回元素相对于视口的正确坐标,无论SVG是否已缩放和/或平移。因此,getBBox()是我应该使用的方法。 - Hasan Parasteh
1个回答

2
如果您有svg元素中的heartdot,您可以使用checkIntersection检查一个元素是否存在于另一个元素的边界内。因此,要检查dot是否在heart内部:
var intersecting = svg.checkIntersection(dot, heart.getBBox());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接