这是一个手绘时钟的案例,是不是很可爱呢!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>手绘时钟</title>
<style type="text/css">
#clockCanvas{
background: url("image02.png") no-repeat center;
}
</style>
</head>
<body onload="drawClock()">
<h3>手绘时钟</h3>
<hr>
<canvas id="clockCanvas" width="600" height="600" >
对不起,您的服务器不支持HTML5画布API。
</canvas>
<script>
var c = document.getElementById("clockCanvas");
var ctx = c.getContext("2d");
//绘制时钟
function drawClock() {
//保存画布的初始绘制状态
ctx.save();
ctx.clearRect(0, 0, 600, 600);
// 设置画笔样式和位置
//设置画布中心为参照点
ctx.translate(300, 300);
ctx.rotate(-Math.PI / 2);
ctx.lineWidth = 6;
ctx.lineCap = "round";
// 画12个刻度
for (var i = 0; i < 12; i++)
{
ctx.beginPath();
ctx.rotate(Math.PI / 6);
ctx.moveTo(210, 0);
ctx.lineTo(240, 0);
ctx.stroke();
}
// 画60分钟对应的刻度
ctx.lineWidth = 5;
for (i = 0; i < 60; i ++)
{
ctx.beginPath();
ctx.moveTo(230, 0);
ctx.lineTo(235,0);
ctx.stroke();
ctx.rotate(Math.PI / 30);
}
var now = new Date();
var s = now.getSeconds();
var m = now.getMinutes();
var h = now.getHours();
if (h > 12)
h -= 12;
//绘制时针
ctx.save();
ctx.rotate(h * (Math.PI / 6) + (Math.PI / 360) * m + (Math.PI / 21600) * s);
ctx.lineWidth = 12;
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(140, 0);
ctx.stroke();
ctx.restore();
//绘制分钟
ctx.save();
ctx.rotate((Math.PI / 30) * m + (Math.PI / 1800) * s);
ctx.strokeStyle = "black";
ctx.lineWidth = 8;
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(200, 0);
ctx.stroke();
ctx.restore();
//绘制秒针
ctx.save();
ctx.rotate(s * Math.PI / 30);
ctx.strokeStyle = "red";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(-40, 0);
ctx.lineTo(250, 0);
ctx.stroke();
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(0, 0, 10, 0, Math.PI * 2, true);
ctx.fill();
//恢复之前的绘图样式
ctx.restore();
//绘制表盘
ctx.lineWidth = 12;
ctx.strokeStyle = "#AEC5EB";
ctx.beginPath();
ctx.arc(0, 0, 270, 0, Math.PI * 2, true);
ctx.stroke();
ctx.restore();
}
setInterval("drawClock()", 1000);
</script>
</body>
</html>