SVGでできる簡単なサンプルアニメーションを書きます。今回は、サークルのアニメーションです。参考サイトで紹介しているSVGのサンプルを、jQueryからJavaScriptに書き換えました。
サークルのアニメーション
0~100の数字を入力するとサークルがアニメーションするサンプルです。元のサンプルからCSSとSVGを一部変更しました。
コード
<!-- HTML --> <svg id="svg" width="200" height="200" viewPort="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <circle r="90" cx="100" cy="100" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle> <circle id="bar" r="90" cx="100" cy="100" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle> <text id="num" x="50%" y="50%">100%</text> </svg> <label for="percent">Type a percent!</label> <input id="percent" name="percent">
/* CSS */ html { height: 100%;} body { height: 100%; padding-top: 2em; text-align: center; } #svg{ display:block; margin: 0 auto; } circle { transition: stroke-dashoffset 1s linear; stroke: #cccccc; stroke-width: 1em; } #bar { stroke: #0034df; } #num{ font-size:2em; text-anchor:middle; dominant-baseline:central; } input { border: 1px solid #666666; padding: 0.5em; box-shadow: none; outline: none !important; margin: 1em auto; text-align: center; }
/* JavaScript */ const circle = document.getElementById('bar'); const num = document.getElementById('num'); const percent = document.getElementById('percent'); const r = circle.getAttribute('r'); //円の半径 const c = Math.PI*(r*2); //円周 percent.addEventListener('change', function(){ const val = numCheck(parseInt(percent.value)); //入力値の取得 const pct = ((100-val)/100)*c; //円周に対する割合 circle.setAttributeNS(null, 'stroke-dashoffset', pct); //入力値に応じてストロークを書く // circle.style.setProperty('stroke-dashoffset', pct); //入力値に応じてストロークを書く num.firstChild.nodeValue = val + '%'; //%を含んで数値を表示 }); //数値で無い場合、数値に置き換える function numCheck(val){ if (isNaN(val)) { val = 100; }else{ if (val < 0) { val = 0;} if (val > 100) { val = 100;} } return val; }
デモ
以下の画像は、上記のコードの実行例です。入力値によって青いバーの割合が変わります。実際に動くところを見たい方は、参考サイトを確認するか、コードをコピーして自分のパソコンで試してください。