当前位置: 首页 > Web前端 > HTML5

如何在画布上画时钟

时间:2023-04-05 11:21:08 HTML5

效果图为上代码:varcanvas=document.getElementById('canvas');varctx=canvas.getContext('2d');varyear,month,day,hour,second,minute;//绘制表格函数drawClockPie(){ctx.beginPath();ctx.lineWidth=2;ctx.strokeStyle='#333';ctx.arc(150,150,146,0,2*Math.PI);ctx.stroke();ctx.closePath();ctx.beginPath();ctx.arc(150,150,6,0,2*Math.PI);ctx.fillStyle='红色';ctx.填充();ctx.closePath();}//绘制时间函数drawClockHours(){for(vari=0,l=12;i<12;i++){ctx.save();ctx.translate(150,150);ctx.rotate(i*1/12*2*Math.PI);ctx.beginPath();ctx.lineWidth=5;ctx.strokeStyle='#333';ctx.moveTo(0,-140);ctx.lineTo(0,-125);ctx.stroke();ctx.closePath();ctx.restore();}}//绘制刻度函数drawClockMins(){for(vari=0,l=60;i<60;i++){ctx.save();ctx.translate(150,150);ctx.rotate(i*1/60*2*Math.PI);ctx.beginPath();ctx.lineWidth=3;ctx.strokeStyle='#333';ctx.moveTo(0,-140);ctx.lineTo(0,-133);ctx.stroke();ctx.closePath();ctx.restore();}}//绘图计时函数drawHourPin(){ctx.save();ctx.translate(150,150);ctx.rotate((小时*60*60+分钟*60+秒)/(12*60*60)*2*Math.PI);ctx.beginPath();ctx.strokeStyle='#333';ctx.lineWidth=3;ctx.moveTo(0,0);ctx.lineTo(0,-40);ctx.stroke();ctx.closePath();ctx.restore();}//绘制分针函数drawMinPin(){ctx.save();ctx.translate(150,150);ctx.rotate((分*60+秒)/(60*60)*2*Math.PI);ctx.beginPath();ctx.strokeStyle='#333';ctx.lineWidth=2;ctx.moveTo(0,0);ctx.lineTo(0,-60);ctx.stroke();ctx.closePath();ctx.restore();}//绘制秒针函数drawSecPin(){ctx.save();ctx.translate(150,150);ctx.rotate(second/60*2*Math.PI);ctx.beginPath();ctx.strokeStyle='红色';ctx.lineWidth=1;ctx.moveTo(0,0);ctx.lineTo(0,-80);ctx.stroke();ctx.closePath();ctx.restore();}//绘制时间文本函数drawText(){hour=hour>=12?小时-12:小时;vartime='now'+year+'year'+month+'month'+day+'day'+hour+'hour'+minute+'minute'+second+'second';ctx.font='15px粗体';ctx.fillText(time,24,350);}//获取时间函数getTimes(){vardate=newDate();年份=date.getFullYear();月=date.getMonth()+1;day=date.getDate();小时=date.getHours();分钟=date.getMinutes();second=date.getSeconds();}setInterval(function(){ctx.clearRect(0,0,600,600);drawClockPie();drawClockHours();drawClockMins();getTimes();drawText();drawHourPin();drawMinPin();drawSecPin();},1000);注:当然,不用这个也可以每秒获取时间,直接每秒递增获取。