LoginSignup
56
63

More than 5 years have passed since last update.

SVGで円をアニメーションさせたい時のMEMO

Last updated at Posted at 2016-08-27

くるっと回る円のアニメーションを作りたい。
Create_a_New_Pen.png
http://codepen.io/melo15/pen/yJmVEJ

結論、下記のように書くと良い。

<svg width="124" height="124">
    <circle cx="62" cy="62" r="60" />
</svg>
svg {
    transform: rotate(-90deg);
}

circle {
    fill: transparent;
    stroke: #4fa8df;
    stroke-width: 4;
    animation: circle 1s infinite;
}

@keyframes circle {
  0% { stroke-dasharray: 0 377; }
  99.9%,to { stroke-dasharray: 377 377; }
}

インラインSVGなので、モダンブラウザは対応していて、
IE8以下、Android2系以下辺りは使えなさそう。
http://caniuse.com/#feat=svg-html5

半径60pxの円を作りたいとすると、
<svg>widthheightには、60px x 2 = 120px
これに、のちのち設定する円の外側の線幅(stroke-width)の4pxを足して、124pxを設定する。
<circle>cxcyには、124pxの半分の値を設定し、円を<svg>の中央に配置する。
rは円の半径で60pxを設定するが、この値によって後々アニメーションさせる時の値が変わってくる。

CSSでは、
<circle>filltransparentにして塗りつぶしなしに設定。
strokestroke-widthを指定して、円の外側に線を表示する。
これをanimationを使って、くるっと回るアニメーションにする。

アニメーションでは、破線を設定するstroke-dasharrayを使う。
stroke-dasharray: 破線の長さ 破線の間隔;
この破線の長さをアニメーションさせる事で、くるっと回るアニメーションとなる。

この時、破線の間隔の値は、円周の長さを設定する必要があり、計算によって導く。
円周の長さは直径 x 3.14で計算する。
今回は、120 x 3.14 = 376.8なので、小数点を切り上げて377とした。
あとは、破線の長さを0から377までアニメーションさせると、くるっと1周するアニメーションとなる。

@-webkit-keyframes circle {
  0% { stroke-dasharray: 0 377; }
  99.9%,to { stroke-dasharray: 377 377; }
}

もし、1周ではなく半分のところで止めたい場合は、377 / 2 = 188.5などを設定すると良い。

最後に、そのままだとアニメーションの開始点が90度ずれてしまうので、
<svg>transform: rotate(-90deg);を設定して、上からくるっと回るアニメーションにする。

同じようなアニメーションのデモも、CodePenにあったのでメモ。
https://codepen.io/kyledws/pen/Gvelt/

56
63
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
63