本文介绍了使用canvas来绘制时钟的案例。
效果图:
代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="clock" width="500" height="500" style="background: #F7F7F7">
您的浏览器不支持canvas标签,无法看到时钟
</canvas>
<script>
var clock = document.getElementById('clock');
var ctx = clock.getContext('2d');
function drawClock() {
//清除画布(相当每隔1s就要清除前一次的画布,否则前一次的痕迹还存在)
ctx.clearRect(0 , 0 , 500 , 500);
//获取当前时间
var nowTime = new Date();
var sec = nowTime.getSeconds();
var min = nowTime.getMinutes();
var hour = nowTime.getHours();
//hour必须加上min转换成的小时浮点数
hour = hour + min / 60.0;
//min也可以加上sec转换成的分钟浮点数
min = min + sec / 60.0;
//将24小时进制转为12小时进制
hour = hour > 12 ? hour - 12 : hour;
//表盘(蓝色)
ctx.lineWidth = 10;
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.arc(250, 250, 200, 0, 360, false);
ctx.closePath();
ctx.stroke();
//刻度
//时刻度
for (var i = 0; i < 12; i++) {
ctx.save();
ctx.lineWidth = 7; //时刻度的粗细
ctx.strokeStyle = "#000"; //时刻度的颜色
ctx.translate(250, 250); //设置异次元空间的0,0点
//再设置旋转角度
ctx.rotate(i * 30 * Math.PI / 180); //每小时旋转30度
ctx.beginPath();
ctx.moveTo(0, -170);
ctx.lineTo(0, -190);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//分刻度
for (var i = 0; i < 60; i++) {
ctx.save();
ctx.lineWidth = 5;
ctx.strokeStyle = "#000";
ctx.translate(250, 250); //设置异次元空间的0,0点
ctx.rotate(i * 6 * Math.PI / 180); //每分钟旋转6度
ctx.beginPath();
ctx.moveTo(0, -180);
ctx.lineTo(0, -190);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//时针
ctx.save();
ctx.lineWidth = 7;
ctx.strokeStyle = "#000";
ctx.translate(250, 250); //设置异次元空间的0,0点
ctx.rotate(hour * 30 * Math.PI / 180); //每小时转30度
ctx.beginPath();
ctx.moveTo(0, -130);
ctx.lineTo(0, 10);
ctx.closePath();
ctx.stroke();
ctx.restore();
//分针
ctx.save();
ctx.lineWidth = 5;
ctx.strokeStyle = "#000";
ctx.translate(250, 250);
ctx.rotate(min * 6 * Math.PI / 180); //每分钟转6度
ctx.beginPath();
ctx.moveTo(0, -160);
ctx.lineTo(0, 15);
ctx.closePath();
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.lineWidth = 3;
ctx.strokeStyle = "red";
ctx.translate(250, 250);
ctx.rotate(sec * 6 * Math.PI / 180); //每秒转6度
ctx.beginPath();
ctx.moveTo(0, -170);
ctx.lineTo(0, 25);
ctx.closePath();
ctx.stroke();
//画时针、分针、秒针交叉的小圆圈
ctx.beginPath();
ctx.arc(0 , 0 , 5 , 0 , 360 , false);
ctx.closePath();
ctx.fillStyle = "gray"; //填充样式
ctx.fill();
//设置笔触样式(秒针已设置了)
ctx.stroke();
//画秒针上的小圆圈
ctx.beginPath();
ctx.arc(0 , -140 , 5 , 0 , 360 , false);
ctx.closePath();
ctx.fill(); //填充样式用上一次的
ctx.stroke(); //笔触样式用上一次的
ctx.restore();
}
drawClock(); //防止刷新后隔一秒钟才加载
//使用setInterval(代码/函数 , 毫秒时间) 让时钟动起来
setInterval(drawClock , 1000); //每隔1s动一次
</script>
</body>
</html>版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u013488580/article/details/47167601