▲TOPへ戻る

【CSS】【Javascript】SVGでつくった円で、一分カウンターを作る方法

SVGで3つの円をつくる

3つの円が重なっている状態

HTML
 <div class="progressCircle">
    <svg viewBox="0 0 100 100">
        //一番後ろの円
        <circle cx="50" cy="50" r="50" class="base" />   
        //真ん中の変化する円
        <circle cx="50" cy="50" r="25" class="circle" /> 
        //手前の秒数が表示される円
        <circle cx="50" cy="50" r="38" class="front" />  
    </svg>
    <div class="seconds">  //秒数を表示するところ
        <span class="second"></span>
    </div>
    </div>
CSS
 .progressCircle{
        height: 100px; 
        width: 100px; 
        display: block; 
        position: relative;
        margin-bottom:10px;
    }
    svg {
        display: block;
        height: 100%;
        width: 100%;
        position: absolute;
        transform: rotate(-90deg);
        top: 0;
        left: 0;
        overflow: visible;
    }
    .circle {
        fill: rgba(0,0,0,0);
        stroke-width: 50;
        stroke-dasharray: 0,157;
        position: relative;
    }
   .seconds{      //秒数を表示させるところ
        font-size:38px;
        font-weight: bold;
        color:#fff;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

CSSでアニメーションさせる

CSS
   .pie {
        stroke: blue;
        webkit-animation-name: pie;
        //*注)あとでJavascriptで書き換えます
        animation: pie 120s linear;
        }
    .front{
        fill: #333;
    }
    @-webkit-keyframes pie {
        50%,100% { stroke-dasharray: 157,157,0,0;}
    }
    @keyframes pie {
        50%,100% { stroke-dasharray: 157,157,0,0;}
    }

javascriptでカウントダウンを表示させる

 function timer(){
    var setTime = 60;   //60秒に設定
    var second = 0;
    const circle = document.querySelector(".circle");
    const seconds = document.querySelector(".second");

    circle.classList.add('pie');
    //先ほどのアニメーションを書き換えてください
    circle.style.animation =  'pie '+ setTime*2 +'s linear';
        var timerId = setInterval(function() {
            second += 1;
            if(second >= setTime){
                clearInterval(timerId);
            }
            countTime = setTime - second;
            seconds.textContent= (countTime % 60);
            if(countTime < 10){  //10秒切ったら文字が赤くなります
                document.querySelector(".seconds").style.color = 'red';
            };
        }, 1000);
    }
    timer();
point

以上、SVGでつくった円をアニメーションさせた、1分カウンターをつくる方法について紹介しました。クイズアプリ等で使ってみてください。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ