JSFiddle - React, Tailwind, and code Playground

by Kyle Lam

HTML

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br>
<button onclick="buttonClicked()" id="button" style="width:100px">click</button>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function drawBase(n){
    for(i=0; i<n; i++){
        ctx.beginPath();
        ctx.arc(95,50,40,arcLength*i+fiveDeg,arcLength*(1+i)-fiveDeg);
        ctx.stroke();
    }
}

function drawState(n, state){
    var tmpStrokeStyle = ctx.strokeStyle;
    var tmpLineWidth = ctx.lineWidth;
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#ff0000';
    ctx.beginPath();
    i=Math.floor(state)+1;
    var fromDegree=arcLength*(state%n)+fiveDeg;
    var toDegree=arcLength*i-fiveDeg;
    if (fromDegree<toDegree){
        ctx.arc(95,50,40,fromDegree,toDegree);
    }
    ctx.stroke();
    ctx.beginPath();    
    var fromDegree=arcLength*i+fiveDeg;
    var toDegree=arcLength*((1+state)%n)-fiveDeg;
    if (fromDegree<toDegree){
        ctx.arc(95,50,40,fromDegree,toDegree);
    }
    ctx.stroke();
    ctx.strokeStyle = tmpStrokeStyle;
    ctx.lineWidth = tmpLineWidth;
}

function drawClear(){
    ctx.clearRect(0, 0, 200, 100);
}


fps=30;
function startAnimation(time, fromState, toState, n){
    if (time <= fps){
        setTimeout(function() {
            drawClear();
            drawBase(n);
            drawState(n, fromState*(1-time/fps)+toState*(time/fps));
            startAnimation(time+1, fromState, toState, n);
        }, 300/fps);
    } 
}


n=2;
arcLength=2*Math.PI/n;
fiveDeg=2*Math.PI/360*5;
selected=-1;

drawBase(n);
drawState(n,selected);


function buttonClicked(){
    if (selected==0){
        n=n+1;
        arcLength=2*Math.PI/n;
        fiveDeg=2*Math.PI/360*5;
    }
    selected=(selected+1)%n;
    document.getElementById("button").innerHTML = selected;
    startAnimation(0, selected-1, selected, n);
}