Qiita Conference 2025

鹿野壮 (@tonkotsuboy_com)

アウトプットは最強の自己投資 〜発信が人生とキャリアを変えた話〜

7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.js SVGで円グラフタイマーを作る

Last updated at Posted at 2018-11-19

Vue.jsでちょっとしたゲームをつくっています。(Vueでつくるってどうなのという話はさておき)
制限時間内に何かをするという内容のゲームでして
制限時間が減少すると円グラフが増えていくようなタイマーを作成してみました。

完成イメージ
aaa_1_1.gif

ソースはこちらです。


<template>
  <div class="pieWp">
    <svg width="100%" height="100%" viewBox="-1 -1 2 2" class="donut">
      <!--背景-->
      <circle cx="0" cy="0" r="1" fill="#dddddd" />
      <path :d=calc :fill=color ></path>
    </svg>
    <p>{{nowTime}}</p>
  </div>
</template>

<style lang="stylus">
  .donut
    transform rotate(-90deg)
</style>

<script>
  import { TweenMax } from 'greensock';
  export default {
    data(){
      return {
        time: 6,
        percent:1,
        color: 'red',
        startX:1,
        startY:0,
        currentPercent:0
      }
    },
    methods: {
      getPieVal(per){
        const x = Math.cos(2 * Math.PI * per);
        const y = Math.sin(2 * Math.PI * per);
        return [x, y];
      },
      start(){
        TweenMax.to(this.$data, this.time, {
          currentPercent : this.$data.percent,
          onComplete:this.complete,
          ease: Power0.easeNone
        });
      },
      complete(){
        alert("Finish")
      }
    },
    computed : {
      calc(){
        const [endX, endY] = this.getPieVal(this.$data.currentPercent);
        const largeArcFlag = this.$data.currentPercent > .5 ? 1 : 0;
        const pathData = [
          `M ${this.$data.startX} ${this.$data.startY}`,
          `A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY}`,
          `L 0 0`,
        ].join(' ');
        return pathData;
      },
      nowTime(){
        return Math.ceil(this.$data.time - this.$data.time * this.$data.currentPercent)
      }
    },
    mounted(){
      setTimeout(()=>{
        this.start()
      },100);
    }
  }
</script>

Codepenはこちら
※上記のコードをボタンでスタートするように変えてます。

SVGのPathタグは分かりづらいですね。
Canvasで作成するほうがどちらかというと直感的に操作できそうです。

こちらを改造したインフォグラフィックサイトなどでつかえそうなグラフ版も作成しましたので、
機会がありましたらご紹介します。

下記の記事を参考にしました。
https://hackernoon.com/a-simple-pie-chart-in-svg-dbdd653b6936

7
8
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?