<!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> body { margin: 0; padding: 0; text-align: center; } </style> </head> <body> <canvas id="canvas"></canvas> <script> let canvasWidth = 600; let canvasHeight = 600; let centerX = canvasWidth / 2; let centerY = canvasHeight / 2; let r = canvasWidth / 2 - 4; let canvas = document.getElementById('canvas'); canvas.width = canvasWidth; canvas.height = canvasHeight; let ctx = canvas.getContext('2d'); let sRad = Math.PI * 2 / 60; let mRad = Math.PI * 2 / 60; let hRad = Math.PI * 2 / 12; function drawClock() { ctx.beginPath(); ctx.clearRect(0, 0, 1000, 1000); ctx.strokeStyle = "orange"; ctx.lineWidth = 4; ctx.arc(centerX, centerY, r, 0, Math.PI * 2, true); ctx.stroke() } function drawHours() { for (let i = 1; i <= 12; i++) { ctx.save(); ctx.beginPath(); ctx.translate(centerX, centerY); ctx.rotate(hRad * i) ctx.translate(-centerX, -centerY); ctx.strokeStyle = "orange"; ctx.lineWidth = 4; ctx.moveTo(centerX, centerY - r); ctx.lineTo(centerX, centerY - r + 24); ctx.font = "26px Arial"; ctx.textAlign = "center"; ctx.fillStyle = "orange"; ctx.fillText(i, centerX, centerY - r + 54); ctx.stroke(); ctx.restore() } } function drawMinutes() { for (let i = 1; i <= 60; i++) { ctx.save(); ctx.beginPath(); ctx.translate(centerX, centerY); ctx.rotate(mRad * i) ctx.translate(-centerX, -centerY); ctx.strokeStyle = "orange"; ctx.lineWidth = 2; ctx.moveTo(centerX, centerY - r); ctx.lineTo(centerX, centerY - r + 16); ctx.stroke(); ctx.restore() } ctx.beginPath(); ctx.arc(centerX, centerY, 20, 0, Math.PI * 2, true); ctx.fillStyle = "orange"; ctx.fill(); } // 画时针 分针 秒针 function drawTimeLine2(rad, lineWidth, offset) { // 时针 ctx.save() ctx.beginPath(); ctx.lineWidth = lineWidth; ctx.translate(centerX, centerY); ctx.rotate(rad) ctx.translate(-centerX, -centerY); ctx.moveTo(centerX, centerY); ctx.lineTo(centerX, centerY - r + offset); ctx.stroke(); ctx.restore() } function render() { requestAnimationFrame(render); drawClock(); drawHours(); drawMinutes(); var timeNow = new Date(); var h = timeNow.getHours(); var m = timeNow.getMinutes(); var s = timeNow.getSeconds(); var sRadNow = sRad * s; var mRadNow = mRad * (m + s / 60); var hRadNow = hRad * (h + m / 60 + s / 3600); drawTimeLine2(sRadNow, 4, 68); drawTimeLine2(mRadNow, 6, 108); drawTimeLine2(hRadNow, 10, 148); } render(); </script> </body> </html>