javascript canvas如何实现简易时钟?本篇文章小编给大家分享一下javascript canvas实现简易时钟代码示例,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
代码如下:
window.onload=function(){ //1.获取画布 var canvas=document.getElementById("canvas"); //2.获取上下文对象(获取画笔) var cx=canvas.getContext("2d"); //3.设置画笔样式 function clock(){ cx.fillStyle="tomato"; //4.绘制图形 //绘制表盘 cx.beginPath(); //绘制圆形 cx.arc(300,300,200,0,Math.PI*2);//设置圆 arc(x,y,r,begin,end,c);x,y:圆的圆的圆心坐标 r:圆的半径 begin,end:开始角度和结束角度;Math.PI=180 Math.PI/180=1度 c:是否按照逆时针进行绘制true:按照逆时 false:顺时针 cx.closePath();//关闭路径 cx.fill();// //绘制时刻度 cx.line; cx.strokeStyle="black"; for(var i=0;i<12;i++){ cx.save(); cx.translate(300,300);//形移 cx.rotate(i*(Math.PI/6)); cx.beginPath(); cx.moveTo(0,-180); cx.lineTo(0,-200); cx.stroke(); cx.closePath(); cx.fillStyle="black";//绘制数字 cx.font="16px blod"; cx.rotate(Math.PI/6); cx.fillText(i+1,-6,-220);//文字 cx.restore(); } //绘制分刻度 for(var i=0;i<60;i++){ cx.save(); cx.translate(300,300); cx.rotate(i*(Math.PI/30)); cx.beginPath(); cx.moveTo(0,-190); cx.lineTo(0,-200); cx.stroke(); cx.closePath(); cx.restore(); } //获取当前时间 var today=new Date(); var hour=today.getHours(); var min=today.getMinutes(); var sec=today.getSeconds(); hour=hour+min/60; //绘制时针 cx.line; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(hour*(Math.PI/6));//旋转 cx.moveTo(0,10); cx.lineTo(0,-130); cx.closePath(); cx.stroke(); cx.restore(); //回滚 //绘制分针 cx.line; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(min*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //回滚 //绘制秒针 cx.line; cx.strokeStyle="black"; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(sec*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //绘制交叉处 cx.fillStyle='#ccc'; cx.strokeStyle="red"; cx.save(); cx.translate(300,300); cx.beginPath(); cx.beginPath(); cx.arc(0,0,4,0,Math.PI*2); cx.closePath(); cx.fill(); cx.closePath(); cx.stroke(); cx.restore(); setTimeout(clock,1000); } // setInterval(clock,1000); clock(); }