javascript canvas实现简易时钟例子
本文实例为大家分享了javascriptcanvas实现简易时钟的具体代码,供大家参考,具体内容如下
钟表 window.onload=function(){ //1.获取画布 varcanvas=document.getElementById("canvas"); //2.获取上下文对象(获取画笔) varcx=canvas.getContext("2d"); //3.设置画笔样式 functionclock(){ 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=180Math.PI/180=1度c:是否按照逆时针进行绘制true:按照逆时false:顺时针 cx.closePath();//关闭路径 cx.fill();// //绘制时刻度 cx.lineWidth=2; cx.strokeStyle="black"; for(vari=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="16pxblod"; cx.rotate(Math.PI/6); cx.fillText(i+1,-6,-220);//文字 cx.restore(); } //绘制分刻度 for(vari=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(); } //获取当前时间 vartoday=newDate(); varhour=today.getHours(); varmin=today.getMinutes(); varsec=today.getSeconds(); hour=hour+min/60; //绘制时针 cx.lineWidth=4; 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.lineWidth=2; 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.lineWidth=1; 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(); }