代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
<meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
<title>绘制时钟</title>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
<script type="text/javascript">
const pi2 =2*Math.PI
let canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
console.log(ctx)
function drawclock(){
ctx.clearRect(0,0,800,800)
//保存初始状态
ctx.save()
// 绘制表盘
ctx.translate(400,400)
ctx.save()
ctx.arc(0,0,200,0,pi2)
//绘制秒、分针刻度
for(let i=0;i<60;i++){
ctx.rotate(pi2/60*i)
ctx.beginPath()
ctx.moveTo(190,0)
ctx.lineTo(210,0)
ctx.lineWidth=2
ctx.strokeStyle='darkgray'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
}
//绘制时针刻度
for(let i=0;i<12;i++){
ctx.rotate(pi2/12*i)
ctx.beginPath()
ctx.moveTo(180,0)
ctx.lineTo(210,0)
ctx.lineWidth=8
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
}
let time = new Date()
let hour = time.getHours()
let min = time.getMinutes()
let sec = time.getSeconds()
hour=hour>12?hour-12:hour
console.log(hour+':'+min+':'+sec)
//绘制秒针
ctx.rotate(-pi2/4)
ctx.rotate(pi2/60*sec)
ctx.beginPath()
ctx.moveTo(-20,0)
ctx.lineTo(180,0)
ctx.strokeStyle='#f44'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
//绘制分针
ctx.rotate(-pi2/4)
ctx.rotate(pi2/60*min+pi2/60/60*sec)
ctx.beginPath()
ctx.lineWidth=4
ctx.moveTo(-15,0)
ctx.lineTo(160,0)
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
//绘制时针
ctx.rotate(-pi2/4)
ctx.rotate(pi2/12*hour+pi2/12/60*min+pi2/12/60/60*sec)
ctx.beginPath()
ctx.lineWidth=6
ctx.moveTo(-10,0)
ctx.lineTo(150,0)
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.restore()
}
drawclock()
setInterval(drawclock,1000)
</script>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。