利用HTML5的canvas来绘制一个时钟;

编写html文件

index.html

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8"
<title>Clock</title>
</head>
<body>
<canvas id="drawClock" width="500" height="500"></canvas>
<script src="js/file1.js"></script>
</body>
</html>

编写js文件

file1.js

var canvas = document.getElementById("drawClock");
var clock = canvas.getContext("2d");

setInterval(drawClock, 1000);

function drawClock() {
//清除像素
clock.clearRect(0, 0, 500, 500);

//绘制表盘
clock.lineWidth = 10;
clock.strokeStyle = "black";
clock.beginPath();
clock.arc(250, 250, 200, 0, 2*Math.PI);
clock.stroke();

//获得需要显示的时间
var time = new Date();
var second = time.getSeconds();
var minute = time.getMinutes();
var hour = time.getHours();//返回0~23之间的整数
hour += minute / 60;
hour = hour > 12 ? hour - 12 : hour;

//绘制表盘上的大刻度
for (var i = 0; i < 12; i++) {
//保存前一个状态
clock.save();
//重新定义画布(0,0)点
clock.translate(250, 250);
clock.lineWidth = 7;
clock.strokeStyle = "black";
clock.rotate(i * 30 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -170);
clock.lineTo(0, -195);
clock.stroke();
clock.restore();
}

//绘制表盘上的小刻度
for (var i = 0; i < 60; i++) {
//保存前一个状态
clock.save();
//重新定义画布(0,0)点
clock.translate(250, 250);
clock.lineWidth = 5;
clock.strokeStyle = "black";
clock.rotate(i * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -180);
clock.lineTo(0, -195);
clock.stroke();
clock.restore();
}

//绘制对应刻度上的数字
for (var i = 0; i < 12; i++) {
clock.save();
clock.translate(250, 250);
var digit = i == 0 ? 12 : i;
var len = 160;
var x = Math.abs(len * Math.sin(i * 30 * Math.PI / 180));
var y = Math.abs(len * Math.cos(i * 30 * Math.PI / 180));
x = i > 6 ? x * -1 : x;
y = i >= 3 && i <= 9 ? y : y * -1;
clock.font = "normal normal bold 10px arial";
clock.fillText(digit, x - 5, y, 50);
clock.restore();
}

//绘制时针
clock.save();
//重新定义画布(0,0)点
clock.translate(250, 250);
clock.lineWidth = 5;
clock.strokeStyle = "black";
clock.rotate(hour * 30 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -100);
clock.lineTo(0, 10);
clock.stroke();
clock.restore();

//绘制分针
clock.save();
clock.translate(250, 250);
clock.lineWidth = 4;
clock.strokeStyle = "black";
clock.rotate(minute * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -125);
clock.lineTo(0, 10);
clock.stroke();
clock.restore();

//绘制秒针
clock.save();
clock.translate(250, 250);
clock.lineWidth = 3;
clock.strokeStyle = "black";
clock.rotate(second * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -150);
clock.lineTo(0, 10);
clock.stroke();
clock.restore();

最终效果图

Draw Clock_i++