本文主要是介绍Html Canvas之动态表盘时钟(带数字刻度数),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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/60hour=hour>12?hour-12:hourvar 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=2cxt.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=1cxt.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=5cxt.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=3cxt.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=1cxt.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=1cxt.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=1cxt.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>
这篇关于Html Canvas之动态表盘时钟(带数字刻度数)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!