前言:
今天利用了点时间学习了如何用canvas来绘制一个动态的时钟,觉得html5的功能实在强大。下面开始分享我的代码以及一些注释。
html部分:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>clock</title> <style type="text/css"> #clock{ text-align: center; } </style> </head> <body> <div> <canvas id="clock" width="200px" height="200px"></canvas> </div> <script type="text/javascript" src="js/clock.js"></script> </body> </html>
JS代码:
var clock = document.getElementById("clock"); var ctx = clock.getContext("2d"); var width = ctx.canvas.width; var height = ctx.canvas.height; var r = width / 2; var rem = width / 200; function drawBackground(){ ctx.save(); //绘制一个圆 ctx.translate(r, r); ctx.beginPath(); ctx.arc(0, 0, r-5, 0, 2 * Math.PI, false); ctx.lineWidth = 10 * rem; ctx.stroke(); //绘制时钟 var hoursArr = [3,4,5,6,7,8,9,10,11,12,1,2]; ctx.font = 18 * rem +'px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; hoursArr.forEach(function(number,i){ var rad = 2*Math.PI / 12 * i; var x = Math.cos(rad) * (r-28 * rem); var y = Math.sin(rad) * (r-28 * rem); ctx.fillText(number,x,y); }); //遍历60个点,绘制时刻点点 for(var i = 0; i < 60;i++){ var rad = 2*Math.PI / 60 * i; var x = Math.cos(rad) * (r-16 * rem); var y = Math.sin(rad) * (r-16 * rem); ctx.beginPath(); if(i % 5 == 0){ ctx.fillStyle = '#000'; ctx.arc(x,y,2 * rem,0,2*Math.PI,false); }else{ ctx.fillStyle = '#ccc'; ctx.arc(x,y,2 * rem,0,2*Math.PI,false); } ctx.fill(); } } //绘制时针线 function drawHour(hour,minute){ ctx.save();//保留 ctx.beginPath(); var rad = 2*Math.PI / 12 * hour; var mrad = 2*Math.PI / 12 / 60 * minute; ctx.rotate(rad+mrad);//旋转 ctx.moveTo(0,10 * rem);//线条起始点 ctx.lineTo(0,-r / 2 - 20 * rem);//线条终点 ctx.lineWidth = 5 * rem;//线条宽度 ctx.lineCap = 'round';//线条圆角 ctx.stroke(); ctx.restore();//还原 } //绘制分针 function drawMinute(minute,second){ ctx.save();//保留 ctx.beginPath(); var rad = 2*Math.PI / 60 * (minute + second / 60); ctx.rotate(rad); ctx.moveTo(0,10 * rem);//线条起始点 ctx.lineTo(0,-r / 2 - 30 * rem);//线条终点 ctx.lineWidth = 3 * rem;//线条宽度 ctx.lineCap = 'round';//线条圆角 ctx.stroke(); ctx.restore();//还原 } //绘制秒针 function drawSecond(second){ ctx.save(); ctx.beginPath(); ctx.fillStyle = '#c14543'; var rad = 2*Math.PI / 60 * second; ctx.rotate(rad); ctx.moveTo(-2 * rem,16 * rem);//线条起始点 ctx.lineTo(2 * rem,16 * rem); ctx.lineTo(1,-r + 18 * rem); ctx.lineTo(-1,-r + 18 * rem); ctx.fill(); ctx.restore(); } //绘制中心原点 function drawDot(){ ctx.beginPath(); ctx.fillStyle = '#fff'; ctx.arc(0,0,3 * rem,0,2*Math.PI,false); ctx.fill(); } //动态的 function draw(){ ctx.clearRect(0,0,width,height); var now = new Date(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); drawBackground(); drawHour(hour,minute); drawMinute(minute,second); drawSecond(second); drawDot(); ctx.restore(); } draw(); setInterval(draw,1000);