如何使用getElementById和getBBox来确定svg的宽度和高度



我有一个D3JS树,并设法将其作为SVG文件下载,但是,我希望viewBox的大小根据SVG框的大小而变化,以实现更好的可视化。建议将getElementById与getBBox结合使用。我不知道如何将正确的svg内容传递给getElementById,并且我提供的任何输入都为null。

由于我怀疑我的代码,我用一个标准的D3JS树示例来尝试函数的使用,但仍然不知道如何使用这些函数。

我的svg选择是

var svg = d3.select("div.svg-container-ar").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.on("wheel.zoom", null) //disable zooming on mouse wheel scroll
.on("dblclick.zoom", null)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")scale(.7,.7)");
zoom.translate([margin.left, margin.top]).scale(.7);

我对getElementById的使用是

// This event is used to download SVG document
$('#download-SVG').click(function() {
var svgElement = document.getElementById('svg');
// console.log(svgElement);
let {width, height} = svgElement.getBBox();
.
.
}

如果有任何帮助,或者有其他方法可以实现可变viewBox大小的要求,我将不胜感激。

function prepareDownload(svgEl) {
// Get bbox of the dom element.
// In some case you may want to get the bbox from an inner <g> element
// where the actual shapes are.
const bBox = svgEl.node().getBBox()
// Set the viewBox of the SVG matching the bbox
svgEl.attr("viewBox", `${bBox.x} ${bBox.y} ${bBox.width} ${bBox.height}`)
// Call the saving function (won't work on Stackovertflow's sandbox)
saveSvg(svgEl.node(), 'my-svg.svg')
// Remove the viewBox so it looks on screen the same as always
svgEl.attr('viewBox', null)
}
function saveSvg(svgEl, name) {
svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg")
const svgData = svgEl.outerHTML
console.log(svgData)
const preface = '<?xml version="1.0" standalone="no"?>rn'
const svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"})
const svgUrl = URL.createObjectURL(svgBlob)
const downloadLink = document.createElement("a")
downloadLink.href = svgUrl
downloadLink.download = name
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
}
document.querySelector('button').addEventListener("click", function() {
prepareDownload(d3.select("svg"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<button>Download</button>
<svg>
<circle style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>
</svg>

最新更新