我有一个用例,设计师为我们提供了一个SVG,我们使用SVG中的某些元素来定位动态创建的元素。
在下面的代码片段中,我尝试使用getBoundingClientRect将rect#overlayTarget与div#overlay重叠:它没有考虑父元素的缩放,并且元素也不重叠。
这个问题的答案在这里不适用,因为它使用了SVG:How to compute getBoundingClientRect() without considering transforms?不可用的element.offsetLeft和element.offsetTop
如何使#overlay和#overlayTarget重叠?
const target = document.querySelector("#overlayTarget");
const position = target.getBoundingClientRect();
const overlay = document.querySelector("#overlay");
overlay.style.top = `${position.y}px`;
overlay.style.left = `${position.x}px`;
overlay.style.width = `${position.width}px`;
overlay.style.height = `${position.height}px`;#overlay {
position: absolute;
background: hotpink;
opacity: 0.3;
width: 100px;
height: 100px;
}<div id="app" style="transform: scale(0.875);">
Test
<div id="overlay"></div>
<svg xmlns="http://www.w3.org/2000/svg" width="1809" height="826" viewBox="0 0 809 826">
<g
id="Main_overview"
data-name="Main overview"
transform="translate(-49.5 -155)"
>
<g
id="overlayTarget"
data-name="DC-DC converter"
transform="translate(400 512)"
>
<rect
id="Rectangle_29"
data-name="Rectangle 29"
width="74"
height="74"
fill="none"
stroke="#47516c"
stroke-width="2"
/>
</g>
</g>
</svg>
</div>
发布于 2020-10-05 19:55:51
如果您不能在转换后的元素之外设置overlay元素,则此答案将有效,但仅适用于一些简单的转换:
在这些情况下,边界框的角不会移出其上/左和下/右方向。旋转或倾斜,大多数3D变换都不会起作用。
然后,您可以通过将带有逆矩阵的position的角点转换为为#app元素设置的角点,来计算覆盖图的结果框值。DOMPoint和DOMMatrix接口有助于实现这一点。
请务必记住,transform设置了隐式position: relative,因此覆盖的top和left值与视口无关。
const app = document.querySelector('#app');
const relative = app.getBoundingClientRect();
const target = document.querySelector("#overlayTarget");
const position = target.getBoundingClientRect();
const matrix = new DOMMatrix(app.style.transform).inverse();
const topleft = new DOMPoint(
position.x - relative.x,
position.y - relative.y
).matrixTransform(matrix);
const bottomright = new DOMPoint(
position.x - relative.x + position.width,
position.y - relative.y + position.height
).matrixTransform(matrix);
const overlay = document.querySelector("#overlay");
overlay.style.top = `${topleft.y}px`;
overlay.style.left = `${topleft.x}px`;
overlay.style.width = `${bottomright.x - topleft.x}px`;
overlay.style.height = `${bottomright.y - topleft.y}px`;#overlay {
position: absolute;
background: hotpink;
opacity: 0.3;
width: 100px;
height: 100px;
}<div id="app" style="transform: scale(0.875);">
Test
<div id="overlay"></div>
<svg xmlns="http://www.w3.org/2000/svg" width="1809" height="826" viewBox="0 0 809 826">
<g
id="Main_overview"
data-name="Main overview"
transform="translate(-49.5 -155)"
>
<g
id="overlayTarget"
data-name="DC-DC converter"
transform="translate(400 512)"
>
<rect
id="Rectangle_29"
data-name="Rectangle 29"
width="74"
height="74"
fill="none"
stroke="#47516c"
stroke-width="2"
/>
</g>
</g>
</svg>
</div>
https://stackoverflow.com/questions/64206235
复制相似问题