时钟源码如下:
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
canvas{
border: 1px solid #cccccc;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="400" height="400"></canvas>
<script>
var mycanvas=document.getElementById('mycanvas');
var ctx=mycanvas.getContext('2d');//设置画布中心点
function play(){
ctx.clearRect(0,0,mycanvas.width,mycanvas.height);
ctx.save();
ctx.translate(mycanvas.width / 2, mycanvas.height / 2);
biaopan();
run();
ctx.restore();
requestAnimationFrame(play);
}
play();
function biaopan() {
ctx.strokeStyle = '#777';
ctx.lineWidth = 5;
//绘制表盘
ctx.beginPath();
ctx.arc(0, 0, 150, 0, 2 * Math.PI);
ctx.stroke();
//刻度
//分针刻度
ctx.lineWidth = 2;
ctx.strokeStyle = 'blue';
for (var i = 0; i < 60; i++) {
ctx.beginPath();
ctx.moveTo(0, -130);
ctx.lineTo(0, -140);
ctx.stroke();
ctx.rotate(2 * Math.PI / 60);
}
//时针刻度
ctx.lineWidth = 6;
ctx.strokeStyle = 'blue';
for (var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.moveTo(0, -120);
ctx.lineTo(0, -140);
ctx.stroke();
ctx.rotate(2 * Math.PI / 12);
}
//数字
ctx.textAlign='center';
ctx.textBaseline='middle';
ctx.font='18px 微软雅黑';
for(var i=1;i<13;i++){
ctx.fillText(i,Math.sin(2*Math.PI/12*i)*110,Math.cos(2*Math.PI/12*i)*-110);
}
}
function run() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
//时针
ctx.save();
ctx.rotate(2 * Math.PI / 12 * h + (2 * Math.PI / 60 * m + 2 * Math.PI / 60 * s / 60) / 12);
ctx.strokeStyle = '#a71';
ctx.lineWidth = 9;
ctx.beginPath();
ctx.moveTo(0, 14);
ctx.lineTo(0, -70);
ctx.stroke();
ctx.restore();
//分针
ctx.save();
//秒针走60 分针走一格
ctx.rotate(2 * Math.PI / 60 * m + 2 * Math.PI / 60 * s / 60);
ctx.lineWidth = 4;
ctx.strokeStyle = '#f71';
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -100);
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.rotate(2 * Math.PI / 60 * s);
ctx.lineWidth = 2;
ctx.strokeStyle = '#f00';
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -120);
ctx.stroke();
ctx.restore();
//中心
ctx.fillStyle = '#777';
ctx.beginPath();
ctx.arc(0, 0, 10, 0, 2 * Math.PI);
ctx.fill();
}
</script>
</body>
</html>