canvas Drawing Dial Clock
- 2021-07-13 04:21:04
- OfStack
Without saying much, please look at the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas Draw the dial </title>
</head>
<body>
<canvas id='box' width="500" height="500" >
Your browser does not support canvas
</canvas>
<script>
var box = document.getElementById('box');
var cxt = box.getContext('2d');
// The clock moves
var timer = null;
function clock(){
var date = new Date();
var h = date.getHours();
h = h + h/60;
h = h>12? h-12:h;
var m = date.getMinutes();
var s = date.getSeconds();
// Clear canvas
cxt.clearRect(0,0,500,500);
// Draw a dial
cxt.strokeStyle = '#f0f';
cxt.lineWidth = 6;
cxt.beginPath();
cxt.arc(250,250,100,0,2*Math.PI);
cxt.stroke();
// Draw a clock scale
for(var i=0; i<12; i++){
cxt.save();
cxt.translate(250,250);
cxt.rotate(30*i*Math.PI/180);
cxt.lineWidth = 3;
cxt.beginPath();
cxt.moveTo(0,-80);
cxt.lineTo(0,-92);
cxt.stroke();
cxt.restore();
}
// Draw a minute scale
for(var i=0; i<60; i++){
cxt.save();
cxt.translate(250,250);
cxt.rotate(6*i*Math.PI/180);
cxt.lineWidth = 2;
cxt.beginPath();
cxt.moveTo(0,-86);
cxt.lineTo(0,-92);
cxt.stroke();
cxt.restore();
}
// Draw an hour hand
cxt.save();
cxt.lineWidth = 5;
cxt.translate(250,250);
cxt.rotate(h*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,6);
cxt.lineTo(0,-40);
cxt.stroke();
cxt.restore();
// Draw a minute hand
cxt.save();
cxt.lineWidth = 3;
cxt.translate(250,250);
cxt.rotate(m*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,8);
cxt.lineTo(0,-60);
cxt.stroke();
cxt.restore();
// Draw a second hand
cxt.save();
cxt.lineWidth = 1;
cxt.translate(250,250);
cxt.rotate(s*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,10);
cxt.lineTo(0,-75);
cxt.stroke();
cxt.restore();
// The small circle in the center of the painting is fixed 3 Root needle
cxt.save();
cxt.beginPath();
cxt.fillStyle = '#0f0';
cxt.lineWidth = 2;
cxt.translate(250,250);
cxt.arc(0,0,2,0,360,false);
cxt.stroke();
cxt.fill();
cxt.restore();
// Draw the garden on the second hand
cxt.save();
cxt.fillStyle = '#f00';
cxt.lineWidth = 2;
cxt.translate(250,250);
cxt.rotate(s*6*Math.PI/180);
cxt.beginPath();
cxt.arc(0,-60,2,0,360,false);
cxt.stroke();
cxt.fill();
cxt.restore();
}
clock();
timer = setInterval(clock,1000);
</script>
</body>
</html>