canvas画一个时钟

时间:2024-01-10 08:14:50

效果图如下

canvas画一个时钟

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script>
var canvas = document.getElementById("canvas");
var can = canvas.getContext("2d");
function drawClock(c){
c.clearRect(0,0,500,500);
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
hours = hours>12?hours-12:hours;
hours = hours+minutes/60;
var time = now.toLocaleString();
console.log(hours,minutes,seconds);
c.beginPath();
c.lineWidth=8;
c.arc(250,250,200,0,Math.PI*2,false);
c.stroke(); for(var i=0;i<12;i++){
c.save();
c.lineWidth=5;
c.translate(250,250);//将起始位置移动到圆心。
c.rotate(i*30*Math.PI/180);//旋转,这里是画刻度的关键,画刻度的线条每次循环都在一个地方,但是画布旋转了。
                        就像切香肠时刀的落点不变,每次将香肠往前推。
c.beginPath();
c.moveTo(0,-180);
c.lineTo(0,-195);
c.closePath();
c.stroke();
c.restore();
}
for(var i=0;i<60;i++){
c.save();
c.lineWidth= 3;
c.translate(250,250);
c.rotate(6*i*Math.PI/180);
c.beginPath();
c.moveTo(0,-190);
c.lineTo(0,-195);
c.closePath();
c.stroke();
c.restore();
} //表盘中心
c.lineWith=1;
c.beginPath();
c.arc(250,250,4,0,360,false);
c.fill();
c.closePath(); //时针
c.save();
c.translate(250,250);
c.rotate(hours*30*Math.PI/180);
c.lineWidth = 7;
c.beginPath();
c.moveTo(0,15);
c.lineTo(0,-120);
c.stroke();
c.closePath();
c.restore(); //分针
c.save();
c.translate(250,250);
c.rotate(minutes*6*Math.PI/180);
c.lineWidth=3;
c.moveTo(0,15);
c.lineTo(0,-135);
c.stroke();
c.restore(); //秒针
c.save();
c.translate(250,250);
c.rotate(seconds*6*Math.PI/180);
c.lineWidth=1;
c.moveTo(0,15);
c.lineTo(0,-160);
c.stroke();
c.beginPath();
c.strokeStyle="red";
c.fillStyle="white";
c.arc(0,-145,5,0,180,false);
c.fill();
c.stroke();
c.closePath(); c.beginPath();
//判断秒数能否被5整除,能整除表示大刻度,反之为小刻度
if(seconds%5==0){
c.moveTo(0,-180);
c.lineTo(0,-195);
c.lineWidth=5;
}else{
c.moveTo(0,-190);
c.lineTo(0,-195);
c.lineWidth=3;
}
//当秒针走到某个刻度时,相应的边为红色。
c.strokeStyle="red";
c.stroke();
c.closePath();
c.restore(); //写时间
c.font="15px 黑体"
c.fillText(time,160,150);
}
setInterval("drawClock(can)",1000);
</script>
</html>