Html Canvas之动态表盘时钟(带数字刻度数)
能够实现指针按标准时间走,并加入一个倒计时。
效果图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>clock</title>
</head>
<body>
<canvas id=mycanvas width=500 height=500 ></canvas>
<script>
var cav=document.getElementById("mycanvas");
var cxt=cav.getContext("2d");
function drawClock(){
cxt.clearRect(0,0,500,500)
var now=new Date()
sec=now.getSeconds()
min=now.getMinutes()
hour=now.getHours()
hour=hour+min/60
hour=hour>12?hour-12:hour
var endTime=new Date("2020/12/19 00:00:00");
var second = parseInt((endTime.getTime()-now.getTime())/1000);
var d = parseInt(second/3600/24); //天数
cxt.fillStyle='red'
cxt.font="15px 楷体"
cxt.fillText("距2021年考研还剩: "+d+"天 ",160,330)
// 画表盘
cxt.beginPath()
cxt.strokeStyle='#999';
cxt.lineWidth=1;
cxt.arc(250,250,205,0,2*Math.PI,false)
cxt.stroke()
cxt.closePath()
cxt.beginPath()
cxt.strokeStyle='black';
cxt.lineWidth=2;
cxt.arc(250,250,190,0,2*Math.PI,false)
cxt.stroke()
cxt.closePath()
// 画时刻度
for(var i=0;i<12;i++){
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=2
cxt.strokeStyle='black'
cxt.rotate(i*30*Math.PI/180)
cxt.moveTo(0,-190)
cxt.lineTo(0,-170)
cxt.stroke()
cxt.restore()
cxt.closePath()
}
// 画分刻度
for(var i=0;i<60;i++){
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=1
cxt.strokeStyle='black'
cxt.rotate(i*6*Math.PI/180)
cxt.moveTo(0,-190)
cxt.lineTo(0,-180)
cxt.stroke()
cxt.restore()
cxt.closePath()
}
//表盘数字
for(var i=0;i<12;i++){
var num=[3,4,5,6,7,8,9,10,11,12,1,2]
cxt.beginPath()
cxt.save()
cxt.translate(235,265)
cxt.fillStyle='black'
cxt.font="50px 黑体"
var x=Math.cos(2*Math.PI/12*i)*140;
var y=Math.sin(2*Math.PI/12*i)*140;
cxt.fillText(num[i],x,y)
cxt.stroke()
cxt.restore()
cxt.closePath()
}
// 画时针
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=5
cxt.strokeStyle='black'
cxt.rotate(30*hour*Math.PI/180)
cxt.moveTo(0,-100)
cxt.lineTo(0,10)
cxt.stroke()
cxt.restore()
cxt.closePath()
// 画分针
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=3
cxt.strokeStyle='black'
cxt.rotate(min*6*Math.PI/180)
cxt.moveTo(0,-130)
cxt.lineTo(0,17)
cxt.stroke()
cxt.restore()
cxt.closePath()
// 画秒针
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=1
cxt.strokeStyle='red'
cxt.rotate(sec*6*Math.PI/180)
cxt.moveTo(0,-150)
cxt.lineTo(0,25)
cxt.stroke()
cxt.restore()
cxt.closePath()
// 画圆心
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=1
cxt.strokeStyle='red'
cxt.fillStyle="#ccc"
cxt.arc(0,0,5,0,2*Math.PI,true)
cxt.stroke()
cxt.fill()
cxt.restore()
cxt.closePath()
// 画秒针末端圆圈
cxt.beginPath()
cxt.save()
cxt.translate(250,250)
cxt.lineWidth=1
cxt.strokeStyle='red'
cxt.fillStyle="#ccc"
cxt.rotate(sec*6*Math.PI/180)
cxt.arc(0,-120,5,0,2*Math.PI,true)
cxt.stroke()
cxt.fill()
cxt.restore()
cxt.closePath()
}
setInterval(drawClock,1000)
</script>
</body>
</html>