本文主要是介绍html圆盘钟表纯js有解释【搬代码】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
结果如图所示:
使用的idear中的html编写
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>圆盘时钟</title>
</head><body>
<div style="display: flex; justify-content: center; align-items: center;">
<!-- 此处的width、height调整圆盘在页面中的位置--><canvas id="clockCanvas" width="800" height="800"></canvas>
</div><script>// 获取画布元素const canvas = document.getElementById('clockCanvas');const ctx = canvas.getContext('2d');// 不断更新时钟setInterval(() => {drawClock();}, 1000);function drawClock() {// 清空画布ctx.clearRect(0, 0, canvas.width, canvas.height);// 绘制圆盘ctx.beginPath();ctx.arc(canvas.width / 2, canvas.height / 2, 150, 0, 2 * Math.PI);ctx.fillStyle = 'lightgray';ctx.fill();// 绘制数字ctx.font = '20px Arial';ctx.fillStyle = '#000';ctx.textAlign = 'center';ctx.textBaseline ='middle';for (var i = 1; i <= 12; i++) {var angle = (i - 3) * (Math.PI / 6);//xy中的 x = a + b * Math.cos(angle);a + 位置a调整的是数字的位置,数字越大越向右下偏移;b的位置设置数字距离中心多远var x = 400 + 140 * Math.cos(angle);var y = 400 + 140 * Math.sin(angle);ctx.fillText(i, x, y);}// 获取当前时间const now = new Date();const hours = now.getHours();const minutes = now.getMinutes();const seconds = now.getSeconds();// 绘制时针const hourAngle = (hours % 12 + minutes / 60) * (2 * Math.PI / 12);ctx.beginPath();ctx.moveTo(canvas.width / 2, canvas.height / 2);ctx.lineTo(canvas.width / 2 + 80 * Math.sin(hourAngle), canvas.height / 2 - 80 * Math.cos(hourAngle));ctx.strokeStyle = 'black';ctx.stroke();// 绘制分针const minuteAngle = (minutes + seconds / 60) * (2 * Math.PI / 60);ctx.beginPath();ctx.moveTo(canvas.width / 2, canvas.height / 2);ctx.lineTo(canvas.width / 2 + 120 * Math.sin(minuteAngle), canvas.height / 2 - 120 * Math.cos(minuteAngle));ctx.strokeStyle = 'black';ctx.stroke();// 绘制秒针const secondAngle = seconds * (2 * Math.PI / 60);ctx.beginPath();ctx.moveTo(canvas.width / 2, canvas.height / 2);ctx.lineTo(canvas.width / 2 + 140 * Math.sin(secondAngle), canvas.height / 2 - 140 * Math.cos(secondAngle));ctx.strokeStyle ='red';ctx.stroke();}
</script>
</body></html>
这篇关于html圆盘钟表纯js有解释【搬代码】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!