canvas 画时钟
<!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>Document</title>
</head>
<body>
<canvas width="800" height="600" id="canvas"></canvas>
</body>
<script>
/** @type {HTMLCanvasElement} */
let canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
function rendrClock () {
ctx.clearRect(0, 0, 800, 600)
ctx.save() //原始
ctx.translate(400, 300)
ctx.rotate(-2 * Math.PI / 4)
ctx.save() //表盘
//绘制表盘
ctx.beginPath()
ctx.arc(0, 0, 200, 0, 2 * Math.PI)
ctx.strokeStyle = "darkgrey"
ctx.lineWidth = 10
ctx.stroke()
ctx.closePath()
/* 绘制分钟刻度 */
for (let j = 0; j < 60; j++) {
ctx.rotate(Math.PI / 30)
ctx.beginPath()
ctx.moveTo(180, 0)
ctx.lineTo(190, 0)
ctx.lineWidth = 2
ctx.strokeStyle = "orange"
ctx.stroke()
ctx.closePath()
}
ctx.restore()
ctx.save() //时钟
/* 绘制时钟刻度 */
for (let i = 0; i < 12; i++) {
ctx.rotate(Math.PI / 6)
ctx.beginPath()
ctx.moveTo(180, 0)
ctx.lineTo(200, 0)
ctx.lineWidth = 6
ctx.strokeStyle = "darkgrey"
ctx.stroke()
ctx.closePath()
}
ctx.restore()
ctx.save()
var time = new Date()
var h = time.getHours()
var m = time.getMinutes()
var s = time.getSeconds()
h = h > 12 ? h - 12 : h
console.log(h + ':' + m + ':' + s);
//绘制秒针
ctx.beginPath()
//根据秒针进行旋转
ctx.rotate(2 * Math.PI / 60 * s)
ctx.moveTo(-30, 0)
ctx.lineTo(170, 0)
ctx.lineWidth = 2
ctx.strokeStyle = "orange"
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
//绘制分针
ctx.beginPath()
//根据秒针进行旋转
ctx.rotate(2 * Math.PI / 60 * m + 2 * Math.PI / 3600 * s)
ctx.moveTo(-20, 0)
ctx.lineTo(150, 0)
ctx.lineWidth = 4
ctx.strokeStyle = "red"
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
//绘制分针
ctx.beginPath()
//根据秒针进行旋转
ctx.rotate(2 * Math.PI / 12 * h + 2 * Math.PI / 60 / 12 * m)
ctx.moveTo(-10, 0)
ctx.lineTo(90, 0)
ctx.lineWidth = 6
ctx.strokeStyle = "darkslategray"
ctx.stroke()
ctx.closePath()
ctx.beginPath()
ctx.arc(0, 0, 10, 0, 2 * Math.PI)
ctx.fillStyle = "#a89"
ctx.fill()
ctx.closePath()
}
setInterval(() => {
ctx.restore()
ctx.restore()
rendrClock()
}, 1000)
</script>
</html>