效果圖:
一、實現時鍾外形時,表盤的刻度和數字書寫
for(var i = 0;i < 60;i++){ if(degree%30 == 0){ cxt.beginPath(); bigX = 400+big_radius*Math.sin(degree*Math.PI/180); //時鍾刻度外面大的半徑的坐標 bigY = 300+big_radius*Math.cos(degree*Math.PI/180); smallX = 400+small_radius*Math.sin(degree*Math.PI/180);//時鍾刻度外面小的半徑的坐標 smallY = 300+small_radius*Math.cos(degree*Math.PI/180); numX = 400+(small_radius-28)*Math.sin(degreeNum*Math.PI/180);//時鍾刻度數字坐標 numY = 300+(small_radius-28)*Math.cos(degreeNum*Math.PI/180); cxt.font = 'bold 55px Arial';//設置時鍾數字樣式 cxt.textAlign = 'center';//數字水平居中 cxt.textBaseline = 'middle';//數字垂直居中 cxt.fillStyle = '#979797'; cxt.moveTo(bigX,bigY); //設置刻度圖像 cxt.lineTo(smallX,smallY); cxt.lineWidth = 10; cxt.fillText(string.toString(),numX,numY);//設置數字圖形 cxt.fill(); cxt.strokeStyle = "#979797"; cxt.stroke(); string = string + 1; if(string == 13){ string = string - 12; } }else{ cxt.beginPath(); cxt.moveTo(400+big_radius*Math.sin(degree*Math.PI/180),300+big_radius*Math.cos(degree*Math.PI/180)); cxt.lineTo(400+small_radius*Math.sin(degree*Math.PI/180),300+small_radius*Math.cos(degree*Math.PI/180)); cxt.lineWidth = 3;//細刻度 cxt.strokeStyle = "#979797"; cxt.stroke(); }
二、設置時鍾表針
cxt.translate(400,300);//首先將坐標設置到canvas中心,后面的rotate才會按照此原點旋轉 //秒針繪制 cxt.beginPath(); cxt.rotate(degreeSecond); cxt.moveTo(-3,60); cxt.lineTo(0,68); cxt.lineTo(3,60); cxt.lineTo(1,-210); cxt.lineTo(0,-215); cxt.lineTo(-1,-210); cxt.closePath(); cxt.fillStyle = '#979797'; cxt.fill(); //分針繪制 cxt.beginPath(); cxt.setTransform(1,0,0,1,400,300,0,0,1); cxt.rotate(degreeMin); cxt.moveTo(-5,40); cxt.lineTo(0,48); cxt.lineTo(5,40); cxt.lineTo(3,-180); cxt.lineTo(0,-185); cxt.lineTo(-3,-180); cxt.closePath(); cxt.fillStyle = '#979797'; cxt.fill(); //時針繪制 cxt.beginPath(); cxt.setTransform(1,0,0,1,400,300,0,0,1); cxt.rotate(degreeHour); cxt.moveTo(-7,20); cxt.lineTo(0,28); cxt.lineTo(7,20); cxt.lineTo(5,-150); cxt.lineTo(0,-155); cxt.lineTo(-5,-150); cxt.closePath(); cxt.fillStyle = '#979797'; cxt.fill();
三、時針隨時間轉動
var disDegreeOfSecond = Math.PI/30; //一秒 秒針走的度數
var disDegreeOfMin = Math.PI/1800; //一秒 分針走的度數
var disDegreeOfHour = Math.PI/21600;//一秒 時針走的度數
//使用setInterval,如果按照毫秒數增加,會出現時鍾不准確的情況,就換了另一種實現方法
setInterval(function(){ cxt.clearRect(0,0,canvas.width,canvas.height); clockStyle(); date = new Date(); hour = date.getHours(); minutes = date.getMinutes(); seconds = date.getSeconds(); degreeS = seconds * disDegreeOfSecond;
degreeM = disDegreeOfMin * (seconds + minutes * 60);
degreeH = disDegreeOfHour * (seconds + minutes * 60 + hour * 3600);
if(hour > 12){ hour -= 12; }
clockPointerMove(degreeS,degreeM,degreeH);
},1000);//這樣表針就不能平滑轉動了
setInterval(function(){
cxt.clearRect(0,0,canvas.width,canvas.height); clockStyle(); degreeS += disDegreeOfSecond * 17/1000;
degreeM += disDegreeOfMin * 17/1000;
degreeH += disDegreeOfHour * 17/1000;
clockPointerMove(degreeS,degreeM,degreeH);
},17); //表針可以平滑轉動,但是時間不太准確