<!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>
<style>
#canvas {
border: 1px solid skyblue;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500">
做兼容:版本太低,请更新版本
<a href="http://www.baidu.com">更新</a>
</canvas>
<script>
var canvas = document.querySelector('#canvas')
var ctx = canvas.getContext('2d')
ctx.translate(50, 50)
setInterval(() => {
ctx.clearRect(0, 0, 500, 500)
var times = new Date()
var h = times.getHours()
var m = times.getMinutes()
var s = times.getSeconds()
var sAngle = (s * 6 - 90) / 180 * Math.PI
var mAngle = (m * 6 - 90) / 180 * Math.PI
var hAngle = (h * 30 - 90 + m / 2) / 180 * Math.PI
for (var i = 0; i < 60; i++) {
// 做一个扇形
ctx.beginPath()
ctx.moveTo(200, 200)
ctx.lineWidth = 1
ctx.arc(200, 200, 200, 6 * i / 180 * Math.PI, 6 * (i + 1) / 180 * Math.PI, false)
ctx.closePath()
ctx.stroke()
}
ctx.beginPath()
ctx.fillStyle = '#fff'
ctx.arc(200, 200, 190, 0, 2 * Math.PI, false)
ctx.fill()
for (var i = 0; i < 12; i++) {
// 做一个扇形
ctx.beginPath()
ctx.moveTo(200, 200)
ctx.lineWidth = 2
ctx.arc(200, 200, 200, 30 * i / 180 * Math.PI, 30 * (i + 1) / 180 * Math.PI, false)
ctx.closePath()
ctx.stroke()
}
ctx.beginPath()
ctx.fillStyle = '#fff'
ctx.arc(200, 200, 180, 0, 2 * Math.PI, false)
ctx.fill()
// 时针
ctx.beginPath()
ctx.moveTo(200, 200)
ctx.lineWidth = 3
ctx.arc(200, 200, 130, hAngle, hAngle, false)
ctx.closePath()
ctx.stroke()
ctx.beginPath()
ctx.moveTo(200, 200)
ctx.lineWidth = 2
ctx.arc(200, 200, 150, mAngle, mAngle, false)
ctx.closePath()
ctx.stroke()
ctx.beginPath()
ctx.moveTo(200, 200)
ctx.lineWidth = 1
ctx.arc(200, 200, 180, sAngle, sAngle, false)
ctx.closePath()
ctx.stroke()
ctx.save()
ctx.translate(200, 200)
ctx.beginPath()
ctx.font = '20px 楷体'
ctx.fillStyle = '#000'
var arr = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]
for (var i = 0; i < arr.length; i++) {
var x = Math.cos(30 / 180 * i * Math.PI) * 165 - 5
var y = Math.sin(30 / 180 * i * Math.PI) * 165 + 5
ctx.fillText(arr[i], x, y)
}
ctx.restore()
ctx.beginPath()
ctx.arc(200, 200, 5, 0, 2 * Math.PI, false)
ctx.fill()
ctx.closePath()
ctx.stroke()
// 文字
ctx.save()
ctx.translate(200, 200)
ctx.font = '30px 楷体'
ctx.fillStyle = '#000'
ctx.textAlign = 'center'
ctx.fillText('hahaha', 0, -120)
ctx.restore()
}, 1000)
</script>
</body>
</html>
实现效果: