Categories
CSS JavaScript Web development

HTML5 Canvas Analog Clock

Canvas Clock JavaScript

Demo:

*to see the Canvas Analog Clock on the website click here.

To create the HTML5 Canvas Analog Clock follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add JavaScript

Step1.

Add HTML

<canvas id="canvas-clock" width="300" height="300"</canvas>

Step2.

Add CSS

Set the colour and the position of the background and elements:

body {
  background-color: #778da9;
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;
}

#canvas-clock {
  position: relative;
  background-color: transparent;  
}

Step3.

Add JavaScript

var canvas = document.getElementById("canvas-clock");
var contex = canvas.getContext("2d");
var radius = canvas.height / 2;
contex.translate(radius, radius);
radius = radius * 0.90
setInterval(drawClock, 1000);

function drawClock() {
  drawFace(contex, radius);
  drawNumbers(contex, radius);
  drawTime(contex, radius);
}

function drawFace(contex, radius) {
  var grad;
  contex.beginPath();
  contex.arc(0, 0, radius, 0, 2*Math.PI);
  contex.fillStyle = '#e0e1dd';
  contex.fill();
  contex.strokeStyle = "#333";
  contex.lineWidth = radius*0.1;
  contex.stroke();
  contex.beginPath();
  contex.arc(0, 0, radius*0.1, 0, 2*Math.PI);
  contex.fillStyle = '#333';
  contex.fill();
}

function drawNumbers(contex, radius) {
  var ang;
  var num;
  contex.font = radius*0.15 + "px Helvetica";
  contex.textBaseline="middle";
  contex.textAlign="center";
  for(num = 1; num < 13; num++){
    ang = num * Math.PI / 6;
    contex.rotate(ang);
    contex.translate(0, -radius*0.85);
    contex.rotate(-ang);
    contex.fillText(num.toString(), 0, 0);
    contex.rotate(ang);
    contex.translate(0, radius*0.85);
    contex.rotate(-ang);
  }
}

function drawTime(contex, radius){
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    
    hour=hour%12;
    hour=(hour*Math.PI/6)+
    (minute*Math.PI/(6*60))+
    (second*Math.PI/(360*60));
    drawHand(contex, hour, radius*0.5, radius*0.07);
    
    minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));
    drawHand(contex, minute, radius*0.8, radius*0.07);
    
    second=(second*Math.PI/30);
    drawHand(contex, second, radius*0.9, radius*0.02);
}

function drawHand(contex, pos, length, width) {
    contex.beginPath();
    contex.lineWidth = width;
    contex.lineCap = "round";
    contex.moveTo(0,0);
    contex.rotate(pos);
    contex.lineTo(0, -length);
    contex.stroke();
    contex.rotate(-pos);
}

Enjoy coding!