震惊!Canvas原来还能这么搞!代码画一个时钟出来
生活随笔
收集整理的這篇文章主要介紹了
震惊!Canvas原来还能这么搞!代码画一个时钟出来
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
學會了Canvas之后,發(fā)現(xiàn)canvas幾乎什么都能畫,看著自己家里的時鐘突發(fā)奇想,能不能利用canvas畫一個時鐘出來呢?說搞就搞!
直接上代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>canvas動態(tài)時鐘</title><style>canvas{margin: 25px;}</style> </head> <body><canvas id="mycanvas" width="520px" height="520px"></canvas><script>var cxt=document.getElementById('mycanvas').getContext('2d')function drawClock(){cxt.clearRect(0,0,520,520)//畫表盤cxt.save()cxt.translate(260,260)cxt.beginPath()cxt.strokeStyle="#4C5A63"cxt.arc(0,0,250,0,2*Math.PI,false)cxt.stroke()cxt.closePath()cxt.beginPath()cxt.strokeStyle="black"cxt.arc(0,0,230,0,2*Math.PI,false)cxt.stroke()cxt.restore()cxt.closePath()//畫時刻度for (var i=0;i<12;i++){cxt.beginPath()cxt.save()cxt.translate(260,260)cxt.lineWidth=4cxt.strokeStyle="#000"cxt.rotate(i*30*Math.PI/180)cxt.moveTo(0,-230)cxt.lineTo(0,-208)cxt.stroke()cxt.restore()cxt.closePath()}//畫分刻度for (var i = 0; i < 60; i++) {cxt.beginPath()cxt.save()cxt.translate(260, 260)cxt.lineWidth = 2cxt.strokeStyle = 'black'cxt.rotate(i * 6 * Math.PI / 180)cxt.moveTo(0, -230)cxt.lineTo(0, -220)cxt.stroke()cxt.restore()cxt.closePath()}//寫時間cxt.beginPath()cxt.save()cxt.translate(260,260)var hourNumbers = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];hourNumbers.map(function (number, i) {var rad = i*30*Math.PI/180;var x = Math.cos(rad) * (230 - 50);var y = Math.sin(rad) * (230 - 50);cxt.textAlign = 'center';cxt.textBaseline = 'middle';cxt.fillStyle="#000"cxt.font = "42px bold Arial";cxt.fillText(number, x, y)});cxt.restore()cxt.closePath()//寫文字var now=new Date()//獲取目前時間sec=now.getSeconds()min=now.getMinutes()hour=now.getHours()var endtime=new Date("2020/12/12 00:00:00")var second=parseInt((endtime.getTime()-now.getTime())/1000)//解析字符串,獲取相差秒數(shù)var day=parseInt(second/3600/24)//獲取天數(shù)cxt.fillStyle="red"cxt.font="20px bold 楷體"cxt.fillText("距2021年考研還剩: "+day+"天",150,350)//畫時針cxt.save()cxt.translate(260,260)cxt.beginPath()cxt.lineWidth=7cxt.strokeStyle="black"cxt.rotate(hour*30*Math.PI/180)cxt.moveTo(0,20)cxt.lineTo(0,-140)cxt.stroke()cxt.closePath()//畫分針cxt.beginPath()cxt.lineWidth=3cxt.strokeStyle="black"cxt.rotate(min*6*Math.PI/180)cxt.moveTo(0,30)cxt.lineTo(0,-150)cxt.stroke()cxt.closePath()//畫秒針cxt.beginPath()cxt.lineWidth=2cxt.strokeStyle="black"cxt.rotate(sec*6*Math.PI/180)cxt.moveTo(0,30)cxt.lineTo(0,-170)cxt.stroke()cxt.closePath()cxt.restore()//在原點畫按鈕cxt.beginPath()cxt.fillStyle="red"cxt.strokeStyle="#F5FEDA"cxt.arc(260,260,7,0,2*Math.PI,false)cxt.fill()cxt.stroke()cxt.closePath()}setInterval(drawClock,1000)</script> </body> </html>效果如下哦
總結(jié)
以上是生活随笔為你收集整理的震惊!Canvas原来还能这么搞!代码画一个时钟出来的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python实现全民K歌歌曲下载
- 下一篇: 纯JS实现省市县三级下拉联动