我正在做一个元素,我们需要让用户上传他们的 SVG 并让他们能够对其进行某些修改。
为此,我们定义了一个根级 SVG 和组,用户上传的 SVG 将在其中呈现。
我面临的问题是,具有不同 ViewBox 设置的不同 SVG 会在根 SVG 中的不同位置呈现。我附上了这个的示例图像和一个 fiddle 来玩它:https://jsfiddle.net/gsp4k6n7/2/
这是在根目录中加载 SVG 的代码:
loadImage = function(svgData) {
var root = document.getElementById('__root_group__');
root.innerHTML = svgData;
}
我已经尝试过 transform: translate(x, y)
但这似乎并不适用于所有情况。例如,以下代码能够使带有 DigitalOcean Logo 的第一张图像居中,但第二张图像偏离中心。
alignImage = function() {
var svg = document.getElementById('__root_svg__');
var group = document.getElementById('__root_group__');
var sr = svg.getBoundingClientRect();
var gr = group.getBoundingClientRect();
var x = (sr.width - gr.width) / 2;
var y = (sr.height - gr.height) / 2;
group.setAttribute('transform', `translate(${x},${y})`);
}
在根 SVG 中水平和垂直居中对齐所有导入的 SVG 的最佳方法是什么?
最佳答案
您的 alignImage()
函数会像这样工作:
alignImage = function() {
var svg = document.getElementById('__root_svg__');
// reference the inserted SVG element
var innerSvg = svg.getElementById('__root_group__').firstElementChild;
var sr = svg.getBoundingClientRect();
//extract the vieBox values - note the more robust RegEx
var vb = innerSvg.getAttribute('viewBox').split(/[,\s]+/);
// do not overwrite existing width/height values
var width = innerSvg.hasAttribute('width') ? innerSvg.getAttribute('width') : vb[2];
var height = innerSvg.hasAttribute('height') ? innerSvg.getAttribute('height') : vb[3];
var x = (sr.width - width) / 2;
var y = (sr.height - height) / 2;
innerSvg.setAttribute('x', x);
innerSvg.setAttribute('y', y);
innerSvg.setAttribute('width', width);
innerSvg.setAttribute('height', height);
}
尽管如此,这并不适用于内部 SVG 大于外部的情况。
关于javascript - 在 SVG 中居中 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43174580/