<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box {
display: block;
margin: 0 auto;
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="box" width="500" height="400"></canvas>
<script>
var myCanvas = document.getElementById('box');
var ctx = myCanvas.getContext('2d');
var width = 500;
var height = 400;
// 计算半径
var r = Math.min(width, height) / 2 - 10; //不让半径靠近外边框,所以减去10
// 第一步需要画圆(表盘);
function drawPan() {
// 表盘边框的颜色;
// 画表盘圆
ctx.arc(width / 2, height / 2, r, 0, 2 * Math.PI);
ctx.strokeStyle = "red";
ctx.stroke();
// 填充表盘底色
ctx.fillStyle = "#fff";
ctx.fill();
// 结束上一个圆,画中心点,
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(width / 2, height / 2, 5, 0, 2 * Math.PI);
ctx.fill();
}
//第二部画刻度
function drawKe() {
ctx.beginPath();
// 对原点进行平移到canvas中心
ctx.fillStyle = "#000";
// 平移原点坐标
ctx.translate(width / 2, height / 2);
for (var i = 0; i < 60; i++) {
if (i % 5 === 0) {
// 画大刻度
// x轴要减去刻度宽度的一半;
ctx.fillRect(0 - 2, -r + 4, 4, 10);
} else {
// 画小刻度
ctx.fillRect(0 - 2, -r + 4, 4, 4);
}
// 先画在旋转,保证第一个在正向;
ctx.rotate(6 * Math.PI / 180);
}
}
//第三步画文字
function drawText() {
ctx.font = '20px 微软雅黑';
// 水平剧中;
ctx.textAlign = 'center';
// 垂直剧中
ctx.textBaseline = 'middle'
// 循环写钟点数
for (var i = 1; i <= 12; i++) {
var x = Math.sin(30 * Math.PI / 180 * i) * (r - 30);
var y = Math.cos(30 * Math.PI / 180 * i) * (r - 30);
// -y+6让数字往下靠点;
ctx.fillText(i, x, -y);
}
}
//第四步画指针
function drawZhen(h, m, s) {
// 每一秒清一次画布,清理 的形状是个正方形,此刻圆心位置在表盘正中心;
ctx.clearRect(-2 * r / 3, -2 * r / 3, 4 * r / 3, 4 * r / 3);
ctx.save(); //3点 保存坐标轴x指向三点的方向
// 先做一个处理,便于指针指向的计算,让x轴由指向三点变为指向12点,
ctx.rotate(-90 * Math.PI / 180);
ctx.save(); //保存坐标轴x指向十二点的方向
// 秒针
ctx.restore();//恢复指针指向十二点
ctx.save();//保存坐标轴x指向十二点的方向
ctx.rotate(s * 6 * Math.PI / 180);
ctx.fillStyle = 'red';
ctx.fillRect(0 - 15, -1, r / 1.5, 2);
// 分针
ctx.restore();//恢复指针指向十二点
ctx.save();//保存坐标轴x指向十二点的方向
ctx.fillStyle = "green";
ctx.rotate(m * 6 * Math.PI / 180);
ctx.fillRect(0 - 15, -2, r / 2, 4)
// 时针
ctx.restore();//恢复指针指向十二点;
ctx.fillStyle = 'orange';
//分针每周一度,时针是分针的十二分之一
ctx.rotate(h * 30 * Math.PI / 180 + m * 6 * Math.PI / 180 / 12)
ctx.fillRect(0 - 15, - 2, r / 3, 4);
ctx.restore();//恢复指针坐标指向3点;
}
// 初始化的方法
function init() {
drawPan();
drawKe();
drawText();
setInterval(() => {
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
drawZhen(h, m, s);
}, 1000)
}
init()
</script>
</body>
</html>
canvas 做时钟
最新推荐文章于 2024-07-02 22:34:09 发布