JSFiddle - React, Tailwind, and code Playground
Slice Clock
by Jennifer Perrin
HTML
<div id="container"></div>
CSS
body { margin-top: 50px; background: #222; }
#container {
width: 202px;
margin: 20px auto 0;
}
JavaScript
window.requestAnimFrame = function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ) {
window.setTimeout(callback, 1000 / 60);
};
}();
var canvas, ctx;
var centerX = 100;
var centerY = 100;
function init() {
canvas = document.createElement('canvas');
canvas.width = 202;
canvas.height = 202;
ctx = canvas.getContext("2d");
ctx.strokeStyle = "white";
document.getElementById('container').appendChild(canvas);
}
function animate() {
window.requestAnimFrame(animate);
draw();
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function toRadian(angle) {
return angle / 180 * Math.PI;
}
function drawSlice(radius, startAngle, endAngle, lineWidth) {
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle, false);
ctx.stroke();
ctx.closePath();
}
function drawTimeSlice(radius, value, lineWidth) {
drawSlice(radius, -Math.PI / 2, toRadian(value - 90), lineWidth);
}
function drawMarkers() {
for (var i = 0; i < 12; i ++) {
drawSlice(90, toRadian(i * 30), toRadian(i * 30 + 1), 8);
}
}
function draw() {
var time = new Date();
var hours = time.getHours() % 12;
var minutes = time.getMinutes();
var seconds = time.getSeconds();
clearCanvas();
drawMarkers();
drawTimeSlice(25, hours * 30, 25);
drawTimeSlice(55, minutes * 6, 15);
drawTimeSlice(75, seconds * 6, 5);
}
init();
animate();