可以在<svg>中居中<g>吗?

时间:2019-04-05 16:27:06

标签: svg

我在网上搜索了,但没有找到解决问题的方法,可以这样做,根据父内容的大小将元素居中。

<svg width="100%" height="100%"  xmlns="http://www.w3.org/2000/svg" stroke="#333">
  <g fill="none" fill-rule="evenodd">
    <g transform="translate(1 1)" stroke-width="2">
      <circle stroke-opacity=".5" cx="18" cy="18" r="18"/>
      <path d="M36 18c0-9.94-8.06-18-18-18">
        <animateTransform
          attributeName="transform"
          type="rotate"
          from="0 18 18"
          to="360 18 18"
          dur="1s"
          repeatCount="indefinite"/>
      </path>
    </g>
  </g>
</svg>

1 个答案:

答案 0 :(得分:2)

我会将装载程序放在symbol中。另外,我将给加载器和svg元素一个viewBox属性。

svg{border:1px solid;}
<svg width="100%"  viewBox="-250 -50 500 100"   xmlns="http://www.w3.org/2000/svg" stroke="#333">
  <symbol id="the_symbol"  viewBox="-2 -2 40 40">
    <g stroke-width="2">
      <circle stroke-opacity=".5" cx="18" cy="18" r="18"/>
      
      <path d="M36 18A18,18 0 0 0 0,18">
        <animateTransform
          attributeName="transform"
          type="rotate"
          from="0 18 18"
          to="360 18 18"
          dur="1s"
          repeatCount="indefinite"/>
      </path>
    </g>
  </symbol>
  <use xlink:href="#the_symbol" x="-20" y="-20" width="36" height="36" fill="none"  />
  
</svg>

更新

OP表示他们希望根svg取各种大小,而加载程序的大小必须始终相同。

//the size and position of the symbol
let o = {x:36,y:18}

function init(){
  
  let p = getsize(o);
  //reset the size and position of the use element
  theUse.setAttributeNS(null,"width",p.x)
  theUse.setAttributeNS(null,"height",p.x)
  theUse.setAttributeNS(null,"x",250-p.y)
  theUse.setAttributeNS(null,"y",50-p.y)
}


// a function to calculate the size and position of the use element
function getsize(o){
var p = svg.createSVGPoint();
p.x= o.x;
p.y= o.y;
p = p.matrixTransform(svg.getScreenCTM().inverse());
return p
}

setTimeout(function() {
		init();
		addEventListener('resize', init, false);
}, 15);
svg{border:1px solid;}
symbol{overflow:visible}
<svg id="svg" width="100%" height="100%"   viewBox="0 0 500 100"   xmlns="http://www.w3.org/2000/svg" stroke="#333">
  <symbol id="the_symbol"  viewBox="0 0 36 36">
    <g stroke-width="2">
      <circle stroke-opacity=".5" cx="18" cy="18" r="18"/>
      
      <path d="M36 18A18,18 0 0 0 0,18">
        <animateTransform
          attributeName="transform"
          type="rotate"
          from="0 18 18"
          to="360 18 18"
          dur="1s"
          repeatCount="indefinite"/>
      </path>
    </g>
  </symbol>
  <use id="theUse" xlink:href="#the_symbol" fill="none"  />
  
</svg>