问题:如何将SVG组元素的中心转换为根SVG的中心。我尝试在transform="translate(x,y)"
元素上使用<g>
,但是此转换仅相对于group元素的左上角进行转换。
案例和目标示例::在以下SVG中,两个矩形<rect>
与<g>
分组在一起。 假设我们不知道组内元素的位置,大小和类型。我们只知道父SVG的宽度/高度。目标是将组的中心(两个矩形的边界框)平移到根SVG的中心。问题是我们不知道组本身的“边界框”的高度/宽度,因此,单独使用transform="translate(x,y)"
时,无法使我们到达根SVG的中心。
<svg width="500px" height="300px" preserveAspectRatio="none" viewBox="0,0,5.0,3.0">
<g transform="translate(0,0)>
<rect x="1" y="0.25" width="0.5" height="0.5" fill="green" />
<rect x="1.25" y="1" width="0.5" height="0.5" fill="red" />
</g>
</svg>
要求:
<g>
中没有什么元素。答案 0 :(得分:1)
您需要某种方式进行计算。我正在使用Javascript:
const SVG_NS = 'http://www.w3.org/2000/svg';
const svg = document.querySelector("svg");
// the viewBox of the svg element splited
let svgVB = svg.getAttribute("viewBox").split(/[ ,]+/);
let o = test.getBBox();
let oCenter = {};//the center of the g#test element
oCenter.x = o.x + o.width/2;
oCenter.y = o.y + o.height/2;
// the valuefor the transform attribute
let tr = `
translate(${-oCenter.x},${-oCenter.y})
translate(${svgVB[2]/2},${svgVB[3]/2})`;
test.setAttributeNS(null, "transform",tr);
// for debugging I'm drawing the bounding box
bbox.setAttributeNS(null, "transform",tr);
function drawRect(o, parent) {
let rect = document.createElementNS(SVG_NS, 'rect');
for (let name in o) {
rect.setAttributeNS(null, name, o[name]);
}
parent.appendChild(rect);
return rect;
}
drawRect(o, bbox);
svg{border:1px solid;}
<svg width="500px" height="300px" preserveAspectRatio="none" viewBox="0,0,5.0,3.0">
<g id="bbox"></g>
<g id="test" transform="translate(0 0)">
<rect x="1" y="0.25" width="0.5" height="0.5" fill="green" />
<rect x="1.95" y="1" width="0.5" height="0.5" fill="red" />
</g>
</svg>
我希望对您有帮助