web関連

【javascript,css】svgで複数の円グラフアニメーション2

前回、svgで複数の円グラフアニメーション作ったけどその続きでレスポンシブに対応させたアニメーション付き円グラフ

前回の続き

レスポンシブに対応した円グラフアニメーション

円グラフが入ってるdiv要素の幅を取得して円グラフに代入することでレスポンシブっぽくしている

htmlとcss

<style>
*{
  box-sizing: border-box;
}
.js_piechart{
  position: relative;
}
.pie_chart{
  transform:rotate(-90deg);/*頂点から始まるように調整*/
  position: relative;
  z-index: 3;
}
.pie_chart circle{
  fill:transparent;/*塗り*/
  stroke-width:10;/*線の幅*/
  stroke-linecap: round;
}
.pie_chart.bg{
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
}
.pie_chart.bg circle{
  stroke: #eee;
}
</style>

<div class="js_piechart" data-chartval="30">
	<svg class="pie_chart">
		<circle style="animation:circle1 2s 2s infinite forwards;" />
	</svg>
	<svg class="pie_chart bg">
		<circle>
	</svg>
</div>

円グラフアニメーションの後ろにを配置してメーターっぽくしてる

jsコード

<script>
jQuery(function($) {
  function circle() {
    var css, rules, value;

    // styleタグを作成
    css = document.createElement('style');
    css.media = 'screen';
    css.type = 'text/css';

    // 追加 ここから

    var e_width = $('.js_piechart').width();
    var e_width_half = e_width / 2;
    var e_circle_width = e_width * 3.14;


    $('.pie_chart').attr({
      width: e_width,
      height: e_width,
    });

    $('circle').attr({
      cx: e_width_half,
      cy: e_width_half,
      r: e_width_half - 5,
    });

    // 追加 ここまで

    var i = 1;
    const list = document.querySelectorAll('.js_piechart');
    var arrayList = [].slice.call(list);

    arrayList.forEach(function(val, index, array) {
      // パーセントの計算
      var num = val.dataset.chartval * (e_circle_width / 100);
      value = '@keyframes circle' + i + '{' + [
        '0%{stroke-dasharray:0 ' + e_circle_width + ';stroke: #1871ad}',
        '100%{stroke-dasharray:' + num + ' ' + e_circle_width +
        ' ;stroke: #1871ad}'
      ].join(' ') + '}';

      // ルールをstyleタグに追加
      rules = document.createTextNode([value].join('n'));
      css.appendChild(rules);
      i++;
    });

    // head内に作成
    document.getElementsByTagName('head')[0].appendChild(css);
  }
  circle();
});

</script>

svgcircleの幅とか位置はjsのほうで入れてる

個人的に使ったサイトでpaddingを抜いた幅をjavascriptでうまく取得することができなかったためjQueryを使ってます

なんでうまくいかなかったんだろう?
一応その時の備忘録

クライアント案件で使ったわけじゃないのでIEは対応していない
それと微妙にずれている気がするから後で調べる

Leave a Comment

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。