JavaScript方法getBBox()用于离屏SVG吗?

4

在不将SVG路径放入DOM中的情况下,是否可能获取它的边界框?

const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '391');
svg.setAttribute('height', '391');
svg.setAttribute('viewBox', "-70.5 -70.5 391 391");
svg.innerHTML = `<rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
<g opacity="0.8">
    <rect x="25" y="25" width="200" height="200" fill="lime" stroke-width="4" stroke="pink" />
    <circle cx="125" cy="125" r="75" fill="orange" />
    <polyline points="50,150 50,200 200,200 200,100" stroke="red" stroke-width="4" fill="none" />
    <line x1="50" y1="50" x2="200" y2="200" stroke="blue" stroke-width="4" />
</g>`;
let box = svg.getBBox();
document.body.innerHTML += `<p>x:${box.x}, y:${box.y}, width:${box.width}, height:${box.height}</p>`;
document.body.appendChild(svg);
box = svg.getBBox();
document.body.innerHTML += `<p>x:${box.x}, y:${box.y}, width:${box.width}, height:${box.height}</p>`;

在这里,您可以看到在图像被放置之前,getBBox() 返回的只是零。但如果我想用这张图片做其他事情,比如将它传递给 WebGL 上下文,但我需要边界框信息怎么办?最优雅的方法难道就是将图像放置在 DOM 中,获取信息,然后删除它吗?

1个回答

5

您需要将您的SVG元素添加到DOM中以获取边界框。

如果您只需要获取边界框数据,您可以轻松地通过CSS使您的SVG不可见:

.svg-hidden{
  visibility:hidden;
  position:absolute;
  left:-1px;
  width: 1px !important;
  height: 1px !important;
  overflow: hidden !important;
}

注意:display:none 不起作用,因此我们使用 visibility:hidden 和绝对定位来防止布局移动。
最后,您可以完全删除 svg。
document.querySelector('.svg-hidden').remove();

const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('class', 'svg-hidden');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('width', '391');
svg.setAttribute('height', '391');
svg.setAttribute('viewBox', "-70.5 -70.5 391 391");
svg.innerHTML = `<rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
<g opacity="0.8">
    <rect x="25" y="25" width="200" height="200" fill="lime" stroke-width="4" stroke="pink" />
    <circle cx="125" cy="125" r="75" fill="orange" />
    <polyline points="50,150 50,200 200,200 200,100" stroke="red" stroke-width="4" fill="none" />
    <line x1="50" y1="50" x2="200" y2="200" stroke="blue" stroke-width="4" />
</g>`;
document.body.appendChild(svg);
let box = svg.getBBox();
document.body.innerHTML += `<p>x:${box.x}, y:${box.y}, width:${box.width}, height:${box.height}</p>`;
// remove svg;
document.querySelector('.svg-hidden').remove();
.svg-hidden{
  visibility:hidden;
  position:absolute;
  left:-1px;
  width: 1px !important;
  height: 1px !important;
  overflow: hidden !important;
}


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