时钟
于2022-12-15 11:15:16发布
42
<!doctype html>
<html>
<head>
<meta charset='UTF-8'/>
</head>
<body>
<canvas width=500 height=500>您的浏览器不支持html5</canvas>
</body>
</html>
<script>
//获取Canvas DOM对象
var canvas = document.getElementsByTagName('canvas')[0];
//获取画笔
var p = canvas.getContext('2d');
function move()
{
//清除画布
p.clearRect(0,0,500,500);
//获取秒
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
var hour = date.getHours();
hour = hour + min / 60 ;
hour = hour > 12 ? hour - 12 : hour;
//表盘
p.strokeStyle = 'blue';
p.lineWidth = 10;
p.beginPath();
p.arc(250,250,200,0,360,false);
p.stroke();
p.closePath();
//分刻度
p.strokeStyle = '#000';
for (i=0; i<12; i++ )
{
p.save();
p.translate(250,250);
p.rotate(i*30*Math.PI / 180);
p.beginPath();
p.moveTo(0,-170);
p.lineTo(0,-190);
p.stroke();
p.closePath();
p.restore();
}
//时刻度
for (i=0; i<60; i++ )
{
p.save();
p.translate(250,250);
p.rotate(i*6*Math.PI / 180);
p.beginPath();
p.lineWidth = 3;
p.moveTo(0,-180);
p.lineTo(0,-190);
p.stroke();
p.closePath();
p.restore();
}
//时针
p.save();
p.translate(250,250);
p.rotate(hour*30*Math.PI / 180);
p.beginPath();
p.moveTo(0,10);
p.lineTo(0,-130);
p.stroke();
p.closePath();
p.restore();
//分针
p.save();
p.translate(250,250);
p.rotate(min*6*Math.PI / 180);
p.beginPath();
p.moveTo(0,15);
p.lineTo(0,-160);
p.stroke();
p.closePath();
p.restore();
//秒针
p.lineWidth = 2;
p.strokeStyle = 'red';
p.save();
p.translate(250,250);
p.rotate(sec*6*Math.PI / 180);
p.beginPath();
p.moveTo(0,25);
p.lineTo(0,-160);
p.stroke();
p.closePath();
//绘制小圆圈
p.beginPath();
p.fillStyle = '#ccc';
p.arc(0,0,5,0,360,false);
p.fill();
p.StrokeStyle = 'red';
p.stroke();
p.closePath();
p.beginPath();
p.fillStyle = '#ccc';
p.arc(0,-140,5,0,360,false);
p.fill();
p.StrokeStyle = 'red';
p.stroke();
p.closePath();
p.restore();
}
move();
setInterval(move,1000);
</script>
运行效果