在学习canvas过程中,做了个时钟demo,效果如图,代码贴在下方
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas 时钟</title>
<style>
* {
margin: 0;
padding: 0;
}
.main {
width: 1000px;
padding: 50px 0;
border: 1px solid #ccc;
margin: 0 auto;
text-align: center;
}
#canvas {
margin: 50px 0;
background-color: deepskyblue;
}
</style>
</head>
<body>
<div class="main">
<canvas id="canvas" width="600" height="600">您的浏览器不支持canvas</canvas>
</div>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
function drawClock() {
//获取当前的时分秒
var now = new Date();
var seconds = now.getSeconds();
var minute = now.getMinutes();
var hour = now.getHours();
//小时分钟必须获取浮点类型,产生偏移
minute = minute + seconds / 60;
hour = hour + minute / 60;
//将24小时转换为12小时
hour = hour > 12 ? hour - 12 : hour;
//画圆
ctx.beginPath();
ctx.lineWidth = 5;
ctx.arc(300, 300, 200, 0, 2 * Math.PI, false);
ctx.strokeStyle = 'blue';
ctx.stroke();
//画时钟的刻度 12个刻度,每个刻度旋转30度
for (var i = 0; i <= 12; i++) {
ctx.save();
ctx.strokeStyle = 'black';
ctx.lineWidth = 7;
ctx.translate(300, 300); //设置画布的原点
ctx.rotate(i * Math.PI / 6);
ctx.beginPath();
ctx.moveTo(0, -172);
ctx.lineTo(0, -192);
ctx.stroke();
ctx.restore();
}
//画秒钟的刻度 60个刻度,每个刻度旋转6度
for (var i = 0; i <= 60; i++) {
ctx.save();
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.translate(300, 300); //设置画布的原点
ctx.rotate(i * Math.PI / 30, 300, 300);
ctx.beginPath();
ctx.moveTo(0, -182);
ctx.lineTo(0, -192);
ctx.stroke();
ctx.restore();
}
//标注小时
ctx.fillStyle = 'deeppink';
ctx.font = '22px 微软雅黑';
ctx.lineWidth = 6;
ctx.fillText(12, 286, 150);
ctx.fillText(1, 370, 170);
ctx.fillText(2, 430, 230);
ctx.fillText(3, 456, 310);
ctx.fillText(4, 430, 390);
ctx.fillText(5, 380, 440);
ctx.fillText(6, 295, 468);
ctx.fillText(7, 215, 446);
ctx.fillText(8, 158, 390);
ctx.fillText(9, 132, 310);
ctx.fillText(10, 156, 230);
ctx.fillText(11, 210, 176);
//画时针
ctx.save();
ctx.lineWidth = 7;
ctx.strokeStyle = 'yellow';
ctx.translate(300, 300);
ctx.rotate(hour * 30 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -140);
ctx.stroke();
ctx.restore();
//画分针
ctx.save();
ctx.lineWidth = 5;
ctx.strokeStyle = 'blue';
ctx.translate(300, 300);
ctx.rotate(minute * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -168);
ctx.stroke();
ctx.closePath();
ctx.restore();
//画秒针
ctx.save();
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.translate(300, 300);
ctx.rotate(seconds * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -186);
ctx.stroke();
ctx.closePath();
ctx.restore();
//setTimeout模拟定时器递归调用,每秒绘制一次
setTimeout(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawClock();
}, 1000)
}
drawClock();
}
}
</script>
</body>