本文转自:http://www.w3cfuns.com/notes/19057/93ad0f7bf3f19cc78c67016cd1567395.html
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<canvas width="1000" height="1000" id="clock">
您的浏览器版本太低,不支持显示时钟的canvas标签
</canvas>
<script>
var clockID = document.getElementById("clock");
var clock = clockID.getContext("2d");
//画时钟的方法
function drawClock(id){
//每次清空画布
clock.clearRect(0,0,1000,1000);
//获取系统当前时间(时 、分 、秒)
var now = new Date();
var sec = now.getSeconds();
sec = sec<10?"0"+sec:sec;
var mins = now.getMinutes();
mins = mins<10?"0"+mins:mins;
var hours = now.getHours();
hours = hours<10?"0"+hours:hours;
//绘制文字,显示系统当前时间
clock.save();
clock.translate(0,500);
clock.fillStyle = "#000";
clock.strokeStyle = "#fff";
clock.font = "24px 微软雅黑";
clock.strokeText("系统当前时间为:" + hours + "时" + mins + "分" + sec + "秒", 100, 100);
clock.fillText("系统当前时间为:" + hours + "时" + mins + "分" + sec + "秒", 100, 100);
clock.restore();
//计算:满60分加一小时
hours = hours + mins / 60;
//计算:将24小时制转化为12小时制
hours = hours>12?hours-12:hours;
//画表盘
clock.beginPath();
clock.lineWidth = 10;
clock.strokeStyle = "#000";
clock.arc(300,300,200,0,360,false);
clock.stroke();
clock.closePath();
//画刻度盘
//时刻度
for(var i=0;i<12;i++){
clock.save();
//将起始点定位到圆心
clock.translate(300,300);
//设置刻度的样式
clock.lineWidth = 7;
clock.strokeStyle = "#000";
//设置旋转角度
clock.rotate(i * 30 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -170);
clock.lineTo(0, -190);
clock.stroke();
clock.restore();
};
//分刻度
for (var j = 0; j < 60; j++){
clock.save();
clock.translate(300, 300);
clock.lineWidth = 3;
clock.strokeStyle = "#000";
clock.rotate(j * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -180);
clock.lineTo(0, -190);
clock.closePath();
clock.stroke();
clock.restore();
};
//时针
clock.save();
clock.translate(300, 300);
clock.lineWidth = 7;
clock.strokeStyle = "#000000";
//设置小时的旋转角度,每转一次走30°
clock.rotate(hours * 30 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, 15);
clock.lineTo(0, -120);
clock.stroke();
clock.closePath();
clock.restore();
//分针
clock.save();
clock.translate(300, 300);
clock.rotate(mins * 6 * Math.PI / 180);
clock.lineWidth = 5;
clock.strokeStyle = "#000";
clock.beginPath();
clock.moveTo(0, 20);
clock.lineTo(0, -160);
clock.stroke();
clock.closePath();
clock.restore();
//秒针
clock.save();
clock.translate(300, 300);
clock.rotate(sec * 6 * Math.PI / 180);
clock.lineWidth = 3;
clock.strokeStyle = "#f00";
clock.beginPath();
clock.moveTo(0, 25);
clock.lineTo(0, -165);
clock.stroke();
clock.closePath();
//秒针圆心处一个小圈
clock.fillStyle = "#fff";
clock.strokeStyle = "#f00";
clock.beginPath();
clock.arc(0, 0, 6, 0, 360, false);
clock.fill();
clock.stroke();
clock.closePath();
//秒针顶部一个小圈
clock.beginPath();
clock.arc(0, -140, 3, 0, 360, false);
clock.fillStyle = "#f00";
clock.stroke();
clock.closePath();
clock.restore();
}
drawClock();
setInterval(drawClock, 1000); //使表针根据系统当前时间转动起来
</script>
</body>
</html>
效果如下: