JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE HTML>
<html>
<head>
<title>Canvas timer</title>
</head>
<body>
<div>
<canvas id="timer" width="100" height="100"></canvas>
<span id="counter">180</span>
</div>
</body>
</html>
CSS
canvas {
-webkit-transform : rotate(-90deg);
-moz-transform : rotate(-90deg);
}
div {background-color:#242424;
position: relative; z-index: 1; height: 100px; width: 100px; }
div span {
position : absolute;
z-index : 1;
top : 50%;
margin-top : -0.6em;
display : block;
width : 100%;
text-align : center;
height : 1.5em;
color : #528f20;
font : 1.5em Arial;
}
JavaScript
window.onload = function() {
canvas = document.getElementById('timer'),
seconds = document.getElementById('counter'),
ctx = canvas.getContext('2d'),
sec = seconds.innerHTML | 0,
countdown = sec;
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var
startAngle = 0,
time = 0,
mins = 0,
secs = 0,
intv = setInterval(function(){
// Making 180 look like 3:00 is not working
if(sec > 59)
{
mins = Math.floor(sec/60);
secs = Math.floor(sec - mins*60);
if(mins < 10) mins = "0" + mins;
if(secs < 10) secs = "0" + secs;
}
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(50, 50, 35, startAngle , endAngle, false);
startAngle = endAngle;
ctx.stroke();
seconds.innerHTML = countdown--;
if (++time > sec) { clearInterval(intv); }
}, 1000);
}