如何旋转svg元素而不影响其中的文本

时间:2019-06-21 09:25:23

标签: html css svg

旋转SVG,从顶部开始加载程序动画。但是,它会旋转其中的文本。如何只一起旋转SVG路径而不影响其中的文本。

试图将旋转单独添加到路径。在这种情况下,两个路径都不对齐为圆

<svg class="loader" id="loader-svg" viewBox="0 0 115 115" data-value="66">

    <path class="bg" d="M 107.14216,57.078488 A 50.444955,50.444955 0 0 1 56.697203,107.52345 50.444955,50.444955 0 0 1 6.252247,57.078488 50.444955,50.444955 0 0 1 56.697203,6.633546 50.444955,50.444955 0 0 1 107.14216,57.078488 Z" style="fill:none;stroke-width:12;stroke-opacity:1" />
    <path class="meter" d="M 107.14216,57.078488 A 50.444955,50.444955 0 0 1 56.697203,107.52345 50.444955,50.444955 0 0 1 6.252247,57.078488 50.444955,50.444955 0 0 1 56.697203,6.633546 50.444955,50.444955 0 0 1 107.14216,57.078488 Z" style="fill:none;stroke-width:12;stroke-opacity:1" stroke-dasharray="316.6" stroke-dashoffset="316.6" />
   <text x="50%" y="50%" id="progress-text" text-anchor="middle" dy=".3em">00:00</text>
</svg>

预期:旋转SVG从顶部启动加载程序,而不影响文本 实际:SVG加载器从3点钟位置开始并且文本正确对齐

1 个答案:

答案 0 :(得分:2)

文本不受旋转的影响。我使用以下方法旋转<path class="meter"

transform="rotate(-90,56.69720697402954,57.07850170135498 )"

这意味着我正在将路径向后旋转90度。旋转中心为:x:56.69720697402954, y:57.07850170135498

旋转中心是svg路径的中心。要获取我正在使用javascript的值:首先,我获取路径的边界框:

let bb = thePath.getBBox();

接下来,我正在使用边界框计算中心;

let center_x = bb.x + bb.width/2;
let center_y = bb.y + bb.height/2;

svg{border:1px solid; width:90vh;}
<svg class="loader" id="loader-svg" viewBox="0 0 115 115" data-value="66">

    <path class="bg" d="M 107.14216,57.078488 A 50.444955,50.444955 0 0 1 56.697203,107.52345 50.444955,50.444955 0 0 1 6.252247,57.078488 50.444955,50.444955 0 0 1 56.697203,6.633546 50.444955,50.444955 0 0 1 107.14216,57.078488 Z" style="fill:none;stroke-width:12; stroke:#ccc;stroke-opacity:1" />
    <path class="meter"  d="M 107.14216,57.078488 A 50.444955,50.444955 0 0 1 56.697203,107.52345 50.444955,50.444955 0 0 1 6.252247,57.078488 50.444955,50.444955 0 0 1 56.697203,6.633546 50.444955,50.444955 0 0 1 107.14216,57.078488 Z" style="fill:none;stroke-width:12;stroke-opacity:1;stroke:gold " stroke-dasharray="317" stroke-dashoffset="300" transform="rotate(-90,56.69720697402954,57.07850170135498 )" />
   <text x="50%" y="50%" id="progress-text" text-anchor="middle" dy=".3em">00:00</text>
</svg>

或者,您可以选择旋转svg元素-90deg,然后向后旋转文本:

#loader-svg{transform:rotate(-90deg);  transform-origin: 50% 50%;}
#progress-text{transform:rotate(90deg); transform-origin: 50% 50%;}