是否可以在不將其放入 dom 的情況下獲取 SVG 路徑的邊界框?
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中,獲取資訊,然后洗掉它嗎?
uj5u.com熱心網友回復:
您需要將 svg 元素附加到 DOM 以獲取 boundingBox。
如果您只需要獲取邊界框資料,您可以通過 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345462.html
標籤:javascript svg
