浏览器缩放破坏svg布局

问题描述 投票:0回答:1

(参考代码段)我试图绘制一条路径,该路径从foreignObject #item-A > div内部的一个元素#item-A的底部到foreignObject]内部的另一个元素#item-B > div的顶部> #item-B。 div的高度是可变的。

对于不同的浏览器缩放级别,路径M ${item_A_div_Bottom - svgOffset.y}值给出不同的结果。这会破坏布局。


我浏览了各种文档以尝试了解这种行为的原因:

window.onload = function() {
  var svgEl = document.querySelector('svg'),
    itemA = document.querySelector('#item-A'),
    itemB = document.querySelector('#item-B'),
    path = document.createElementNS("http://www.w3.org/2000/svg", 'path');

  const svgOffset = svgEl.getBoundingClientRect();
  const {
    a
  } = svgEl.getScreenCTM();

  const {
    x: item_A_BBoxX,
  } = itemA.getBBox();

  const {
    bottom: item_A_div_Bottom
  } = document.querySelector(`#item-A > div`).getBoundingClientRect();

  const {
    y: item_B_BBoxY,
  } = document.querySelector(`#item-B`).getBBox();

  const path_d = `
    M ${item_A_BBoxX},${(item_A_div_Bottom - svgOffset.y) * (1 / a)}
    V ${item_B_BBoxY}
  `;

  path.setAttribute('d', path_d);
  path.setAttribute('stroke', 'red');
  path.setAttribute('stroke-width', '2px');
  svgEl.appendChild(path);
}
#header {
  width: 100%;
  height: 30px;
  background-color: purple;
}

#svg-wrapper {
  display: flex;
  justify-content: center;
  height: 600px;
  width: 100%;
  background-color: grey;
}

svg {
  width: 80%;
  height: 100%;
}

foreignObject {
  background-color: black;
}
<div id="header">Header</div>
<div id="svg-wrapper">
  <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <style>
    div {
      color: white;
      font: 18px serif;
      height: 40px;
      overflow: auto;
      background-color: black;
    }
  </style>

  <foreignObject id="item-A" x="20" y="20" width="60" height="30">
    <div xmlns="http://www.w3.org/1999/xhtml">
      Item-A
    </div>
  </foreignObject>
  
  <foreignObject id="item-B" x="20" y="120" width="60" height="30">
    <div xmlns="http://www.w3.org/1999/xhtml">
      Item-B
    </div>
  </foreignObject>
</svg>
</div>

如果放大或缩小然后重新运行代码段,则路径位置和长度都会改变。

如何防止在不同的缩放级别下破坏布局?

(参考代码段)我试图绘制一条路径,从一个元素#item-A> div到foreignobject#item-A的内部到另一个元素#item-B的顶部> div到foreignObject#item-B的内部。 ...

javascript html svg graphics transformation
1个回答
0
投票

element.getBoundingClientRect()返回的属性值随浏览器缩放而变化。如MDN web docs中给出的>

Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。 ....

© www.soinside.com 2019 - 2024. All rights reserved.