- varclock = document.getElementById('canvas');
- varcxt = clock.getContext('2d');
- function drawClock() {
- cxt.clearRect(0,0,500,500);
- //获取一个时间对象
- varnow =new Date();
- varsec = now.getSeconds();
- varmin = now.getMinutes();
- varhour = now.getHours();
- //小时必须获取浮点类型hour = hour+min/60;//这里存在一个时间格式,要将24小时制转化为12小时制hour = hour>12?hour-12:hour;
- //表盘(蓝色)cxt.lineWidth = 10;
- cxt.strokeStyle = '#ABCDEF';
- cxt.beginPath();
- cxt.arc(250,250,200,0,360,false);
- cxt.closePath();
- cxt.stroke();
- //刻度
- //时刻度
- for(vari=0; i<12; i++){
- cxt.save();
- cxt.lineWidth = 7;
- cxt.strokeStyle = '#000';
- //设置0,0点cxt.translate(250,250);
- //设置旋转角度cxt.rotate(i*30*Math.PI/180);//角度 = *MAth.PI/180=弧度
- cxt.beginPath();
- cxt.moveTo(0,-170);
- cxt.lineTo(0,-190);
- cxt.closePath();
- cxt.stroke();
- cxt.restore();
- }
- //分刻度
- for(vari=0; i<60; i++){
- cxt.save();
- cxt.lineWidth = 5;
- cxt.strokeStyle = '#000';
- cxt.translate(250,250);
- //设置旋转角度cxt.rotate(i*6*Math.PI/180); cxt.beginPath();
- cxt.moveTo(0,-180);
- cxt.lineTo(0,-190);
- cxt.stroke();
- cxt.closePath();
- cxt.restore();
- }
- //时针
- cxt.save();
- //设置时针风格cxt.lineWidth = 7;
- cxt.strokeStyle = '#000'
- cxt.translate(250,250);
- cxt.rotate(hour*30*Math.PI/180); cxt.beginPath();
- cxt.moveTo(0,-130);
- cxt.lineTo(0,10);
- cxt.stroke();
- cxt.closePath();
- cxt.restore();
- //分针
- cxt.save();
- cxt.lineWidth = 5;
- cxt.strokeStyle = '#000'
- cxt.translate(250,250);
- cxt.rotate(min*6*Math.PI/180); cxt.beginPath();
- cxt.moveTo(0,-150);
- cxt.lineTo(0,15);
- cxt.stroke();
- cxt.closePath();
- cxt.restore();
- //秒针
- cxt.save();
- cxt.strokeStyle = 'red';
- cxt.lineWidth = 3;
- cxt.translate(250,250);
- cxt.rotate(sec*6*Math.PI/180); cxt.beginPath();
- cxt.moveTo(0,-170);
- cxt.lineTo(0,20);
- cxt.stroke();
- cxt.closePath();
- //画出时针,分针,秒针的交叉点
- cxt.beginPath();
- cxt.arc(0,0,5,0,360,false);
- cxt.closePath();
- cxt.fillStyle = "gray";
- cxt.fill();
- cxt.strokeStyle = 'red';
- cxt.stroke();
- //设置秒针的小圆点
- cxt.beginPath();
- cxt.arc(0,-135,5,0,360,false);
- cxt.closePath();
- cxt.fillStyle = "gray";
- cxt.fill();
- cxt.strokeStyle = 'red';
- cxt.stroke();
- cxt.restore();
- }
- drawClock();
- //使用setInterval(代码,毫秒时间) 让时钟动起来setInterval(drawClock,1000);
来源: http://www.bubuko.com/infodetail-1955857.html