如何将SVG组元素转换为根SVG的中心?

时间:2018-08-28 01:59:56

标签: svg

问题:如何将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>

要求:

  • 该解决方案只能使用纯SVG。不能使用CSS或外部库。
  • 使用Python进行基本计算是可以的。但是,请记住,<g>中没有什么元素。
  • 不得更改根SVG的坐标系(viewBox,宽度,高度),因为在示例用例中,这些坐标系用于将实际空间单位(例如:毫米)转换为最终应用程序的像素。

enter image description here

1 个答案:

答案 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>

我希望对您有帮助