<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>钟表案例</title>
<style>
canvas {
border: 1px solid red;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
</head>
<body>
<canvas width="600" height="600" id="canvas"></canvas>
<script>
window.onload = function () {
let canvas = document.querySelector('#canvas');
if (!canvas.getContext) return;
let ctx = canvas.getContext('2d');
setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw();
}, 1000);
draw();
function draw() {
ctx.save();
// 设置表盘的默认样式
ctx.lineWidth = 8;
ctx.strokeStyle = 'yellow';
ctx.translate(300, 300); // 先平移坐标原点,然后在使用rotate,不然不起作用,画不出图
ctx.rotate(-90 * Math.PI / 180);
ctx.lineCap = 'round';
// 绘制表盘
ctx.beginPath();
ctx.lineWidth = 14;
ctx.strokeStyle = 'green';
ctx.arc(0, 0, 140, 0, 360 * Math.PI / 180);
ctx.stroke();
// 绘制时针
ctx.save();
ctx.lineWidth = 10;
ctx.strokeStyle = 'red';
ctx.beginPath();
for (let i = 0; i < 12; i++) {
ctx.moveTo(100, 0);
ctx.lineTo(120, 0);
ctx.rotate(30 * Math.PI / 180);
ctx.stroke();
}
ctx.restore();
// 绘制分针
ctx.save();
ctx.lineWidth = 6;
ctx.strokeStyle = 'blue';
ctx.beginPath();
for (let i = 0; i < 60; i++) {
if (i % 5 !== 0) {
ctx.moveTo(110, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.rotate(6 * Math.PI / 180);
}
ctx.restore();
// 获取当前时间
let date = new Date();
let s = date.getSeconds(); // 秒数
let m = date.getMinutes() + s / 60; // 具体的分钟数
let h = date.getHours() + m / 60; // 具体的小时数
h = h > 12 ? h - 12 : h; // 把24小时制转为12小时制
// 绘制时针
ctx.save();
ctx.lineWidth = 14;
ctx.strokeStyle = 'purple';
ctx.rotate(h * 30 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(60, 0);
ctx.stroke();
ctx.restore();
// 绘制分针
ctx.save();
ctx.lineWidth = 12;
ctx.strokeStyle = 'orange';
ctx.rotate(m * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(85, 0);
ctx.stroke();
ctx.restore();
// 绘制秒针
ctx.save();
ctx.lineWidth = 6;
ctx.strokeStyle = 'deeppink';
ctx.rotate(s * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(90, 0);
ctx.stroke();
// 绘制表芯
ctx.fillStyle = 'black';
ctx.arc(0, 0, 10, 0, 360 * Math.PI / 180);
ctx.fill();
ctx.beginPath();
ctx.strokeStyle = 'orange';
ctx.arc(100, 0, 8, 0, 360 * Math.PI / 180);
ctx.stroke();
ctx.restore();
ctx.restore();
}
}
</script>
</body>
</html>
记录一次canvas学习--绘制时钟
最新推荐文章于 2022-07-11 21:13:27 发布
6224

被折叠的 条评论
为什么被折叠?



