效果如图
代码如下
<!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>canvas时钟</title>
<style>
html body {
margin: 0;
padding: 0;
}
#canvas {
display: block;
margin: 30px auto 0px;
background: #dddddd
}
.figure-time {
margin-top: 10px;
text-align: center;
font-size: 50px;
font-weight: normal;
}
.seconds {
margin-left: 20px;
font-size: 40px;
}
</style>
</head>
<body>
<div class="time">
<canvas id="canvas" width="300" height="300">您的浏览器不支持canvas,<a href="https://www.google.cn/intl/zh-CN/chrome/">立即升级</a></canvas>
<p class="figure-time"><span class="hours"></span><span>:</span><span class="minutes"></span><span class="seconds"></span></p>
</div>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas')
if (canvas.getContext) { //处理兼容
var ctx = canvas.getContext('2d')
var cw = canvas.width,
ch = canvas.height
const PI = Math.PI
var hours = document.getElementsByClassName('hours')[0],
minutes = document.getElementsByClassName('minutes')[0],
seconds = document.getElementsByClassName('seconds')[0]
ctx.translate(cw / 2, ch / 2) //先将坐标轴移至画板中心
run()
setInterval(run, 1000) //每次隔1秒都重新绘制时钟
function run() {
ctx.clearRect(-cw, -ch, 2 * cw, 2 * ch)
//表盘
ctx.save()
ctx.strokeStyle = "#000"
ctx.lineWidth = 10
ctx.lineCap = "round"
ctx.beginPath()
ctx.arc(0, 0, 140, 0, 2 * PI, false)
ctx.stroke()
ctx.restore()
//刻度
ctx.save()
ctx.strokeStyle = "#000"
ctx.lineWidth = 8
ctx.lineCap = "round"
for (var i = 0; i < 12; i++) {
ctx.rotate(2 * PI / 12)
ctx.beginPath()
ctx.moveTo(0, -125)
ctx.lineTo(0, -105)
ctx.stroke()
}
for (var i = 0; i < 60; i++) {
if (i % 5 != 0) {
ctx.lineWidth = 5
ctx.beginPath()
ctx.moveTo(0, -125)
ctx.lineTo(0, -120)
ctx.stroke()
}
ctx.rotate(2 * PI / 60)
}
ctx.restore()
//获取时间
var time = new Date()
var s = time.getSeconds(),
m = time.getMinutes(),
h = time.getHours()
hours.innerHTML = h < 10 ? "0" + h : h
minutes.innerHTML = m < 10 ? "0" + m : m
seconds.innerHTML = s < 10 ? "0" + s : s
m = m + s / 60,
h = h + m / 60
h = h > 12 ? h - 12 : h
//表针
//时
ctx.save()
ctx.rotate(h * 2 * PI / 12)
ctx.lineWidth = 10
ctx.lineCap = "round"
ctx.beginPath()
ctx.moveTo(0, 20)
ctx.lineTo(0, -70)
ctx.stroke()
ctx.restore()
//分
ctx.save()
ctx.rotate(m * 2 * PI / 60)
ctx.lineWidth = 7
ctx.lineCap = "round"
ctx.beginPath()
ctx.moveTo(0, 35)
ctx.lineTo(0, -110)
ctx.stroke()
ctx.restore()
//秒
ctx.save()
ctx.rotate(s * 2 * PI / 60)
ctx.strokeStyle = "#f00"
ctx.lineWidth = 3
ctx.lineCap = "round"
ctx.beginPath()
ctx.moveTo(0, 40)
ctx.lineTo(0, -80)
ctx.stroke()
ctx.beginPath()
ctx.arc(0, -90, 8, 0, 2 * PI, false)
ctx.moveTo(0, -100)
ctx.lineTo(0, -120)
ctx.stroke()
ctx.restore()
//中间的大红点
ctx.save()
ctx.fillStyle = "#f00"
ctx.beginPath()
ctx.arc(0, 0, 8, 0, 2 * PI, false)
ctx.fill()
ctx.restore()
}
}
}
</script>
</body>
</html>
来都来了,不妨点击一下我的博客呗