clock code html

Solutions on MaxInterview for clock code html by the best coders in the world

showing results for - "clock code html"
María
26 Aug 2020
1<!DOCTYPE html>
2<html>
3<body>
4
5<canvas id="canvas" width="400" height="400"
6style="background-color:#333">
7</canvas>
8
9<script>
10var canvas = document.getElementById("canvas");
11var ctx = canvas.getContext("2d");
12var radius = canvas.height / 2;
13ctx.translate(radius, radius);
14radius = radius * 0.90
15setInterval(drawClock, 1000);
16
17function drawClock() {
18  drawFace(ctx, radius);
19  drawNumbers(ctx, radius);
20  drawTime(ctx, radius);
21}
22
23function drawFace(ctx, radius) {
24  var grad;
25  ctx.beginPath();
26  ctx.arc(0, 0, radius, 0, 2*Math.PI);
27  ctx.fillStyle = 'white';
28  ctx.fill();
29  grad = ctx.createRadialGradient(0,0,radius*0.95, 0,0,radius*1.05);
30  grad.addColorStop(0, '#333');
31  grad.addColorStop(0.5, 'white');
32  grad.addColorStop(1, '#333');
33  ctx.strokeStyle = grad;
34  ctx.lineWidth = radius*0.1;
35  ctx.stroke();
36  ctx.beginPath();
37  ctx.arc(0, 0, radius*0.1, 0, 2*Math.PI);
38  ctx.fillStyle = '#333';
39  ctx.fill();
40}
41
42function drawNumbers(ctx, radius) {
43  var ang;
44  var num;
45  ctx.font = radius*0.15 + "px arial";
46  ctx.textBaseline="middle";
47  ctx.textAlign="center";
48  for(num = 1; num < 13; num++){
49    ang = num * Math.PI / 6;
50    ctx.rotate(ang);
51    ctx.translate(0, -radius*0.85);
52    ctx.rotate(-ang);
53    ctx.fillText(num.toString(), 0, 0);
54    ctx.rotate(ang);
55    ctx.translate(0, radius*0.85);
56    ctx.rotate(-ang);
57  }
58}
59
60function drawTime(ctx, radius){
61    var now = new Date();
62    var hour = now.getHours();
63    var minute = now.getMinutes();
64    var second = now.getSeconds();
65    //hour
66    hour=hour%12;
67    hour=(hour*Math.PI/6)+
68    (minute*Math.PI/(6*60))+
69    (second*Math.PI/(360*60));
70    drawHand(ctx, hour, radius*0.5, radius*0.07);
71    //minute
72    minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));
73    drawHand(ctx, minute, radius*0.8, radius*0.07);
74    // second
75    second=(second*Math.PI/30);
76    drawHand(ctx, second, radius*0.9, radius*0.02);
77}
78
79function drawHand(ctx, pos, length, width) {
80    ctx.beginPath();
81    ctx.lineWidth = width;
82    ctx.lineCap = "round";
83    ctx.moveTo(0,0);
84    ctx.rotate(pos);
85    ctx.lineTo(0, -length);
86    ctx.stroke();
87    ctx.rotate(-pos);
88}
89</script>
90
91</body>
92</html>
93