canvas绘制时钟
- canvas绘制时钟
- 时间:2021年4月20日
- 类型:js练习
- 人员:杨标
效果图
案例说明
本次案例采用 HTML+CSS+JavaScript的方式完成,主要使用了JavaScript里面的canvas来绘制一个时钟,同时对定时器setInterval做了使用
案例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时钟</title>
<style>
.box {
margin-top: 100px;
text-align: center;
}
#clock {
border: 1px solid #808080;
}
</style>
</head>
<body>
<div class="box">
<canvas id="clock" width="400" height="400"></canvas>
</div>
</body>
<script>
var clockDOM = document.querySelector("#clock");
var ctx = clockDOM.getContext("2d");
var width = ctx.canvas.width;
var height = ctx.canvas.height;
var r = width / 2;
function drawBackground() {
ctx.save();
// 平移原点
ctx.translate(r, r);
ctx.lineWidth = 8;
ctx.beginPath();
ctx.arc(0, 0, r - 4, 0, 2 * Math.PI, false);
ctx.stroke();
ctx.fillStyle = "#000000";
ctx.font = "32px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var hourNumber = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];
hourNumber.forEach(function (item, index) {
var x = Math.cos(Math.PI * 2 / 12 * index) * (r - 35);
var y = Math.sin(Math.PI * 2 / 12 * index) * (r - 35);
ctx.fillText(item, x, y);
});
//画小圆点
for (var i = 0; i < 60; i++) {
var x = Math.cos(2 * Math.PI / 60 * i) * (r - 16);
var y = Math.sin(2 * Math.PI / 60 * i) * (r - 16);
ctx.beginPath();
if (i % 5 == 0) {
ctx.fillStyle = "#000000";
ctx.arc(x, y, 5, 0, 2 * Math.PI, false);
} else {
ctx.fillStyle = "#808080";
ctx.arc(x, y, 5, 0, 2 * Math.PI, false);
}
ctx.fill();
}
}
function drawHour(hour, minute) {
ctx.save();
ctx.lineWidth = 7;
ctx.lineCap = "round";
var rad = 2 * Math.PI / 12 * hour;
var rad2 = 2 * Math.PI / 12 / 60 * minute;
ctx.rotate(rad + rad2);
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(0, -r + 100);
ctx.stroke();
ctx.restore();
}
function drawMinute(minute) {
ctx.save();
ctx.lineWidth = 5;
ctx.lineCap = "round";
var rad = 2 * Math.PI / 60 * minute;
ctx.rotate(rad);
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(0, -r + 80);
ctx.stroke();
ctx.restore();
}
function drawSecond(second) {
ctx.save();
ctx.lineWidth = 3;
ctx.lineCap = "round";
ctx.strokeStyle = "#FF0000";
var rad = 2 * Math.PI / 60 * second;
ctx.rotate(rad);
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(0, -r + 60);
ctx.stroke();
ctx.restore();
}
function drawDot() {
ctx.beginPath();
ctx.fillStyle = "#ececec";
ctx.arc(0, 0, 5, 0, 2 * Math.PI, false);
ctx.fill();
}
function draw(){
ctx.clearRect(0,0,width,height);
var d= new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
drawBackground();
drawHour(hour,minute);
drawMinute(minute);
drawSecond(second)
drawDot();
ctx.restore();
}
setInterval(draw,1000);
</script>
</html>
评论区