<canvas>您的浏览器不支持 HTML5 canvas 标签。</canvas>
var c=document.getElementById("myFirstCanvas"); var ctx=c.getContext("2d"); //画指针 function drawPointer(isRect,color,value,angle,startX,startY,endX,endY,arg){ ctx.save(); //先保存当前画布 ctx.fillStyle = color; //设置画笔颜色 ctx.translate(400,300); //重置异次元空间的原点坐标 ctx.rotate(value*angle*Math.PI/180); //设置旋转的角度,参数是弧度 ctx.beginPath(); ctx.moveTo(startX,startY); if(isRect){ ctx.rect(startX,startY,arg[0],arg[1]) }else{ ctx.lineTo(arg[0],arg[1]); ctx.lineTo(endX,endY); ctx.lineTo(arg[2],arg[3]); ctx.closePath(); //先关闭闭合路径,再绘制 } ctx.fill(); //开始绘制 ctx.restore(); //将旋转后的线段返回给画布 } //画刻度 function drawScale(size,color,value,startX,startY,endX,endY,isText,isRect,arg){ for(var i = 0;i < size;i++){ drawPointer(isRect,color,value,i,startX,startY,endX,endY,arg); if(isText){ ctx.save(); ctx.translate(120,35); var newX = parseInt(270*(1+Math.sin(value*i*Math.PI/180))); var newY = parseInt(270*(1-Math.cos(value*i*Math.PI/180))); ctx.beginPath(); ctx.font = "25px Arial"; if(i == 0){ ctx.fillText(12,newX,newY); }else{ ctx.fillText(i,newX,newY); } ctx.closePath(); ctx.restore(); } } } //画时钟 function drawClock(){ ctx.clearRect(0,0,800,600); //清空整个画布 var now = new Date(); //取出系统时间读出时分秒 var s = now.getSeconds(); var m = now.getMinutes(); var h = now.getHours(); m += s/60; h += m/60; if(h > 12) h -= 12; ctx.beginPath(); ctx.lineWidth = 10; ctx.strokeStyle = "#9ef1c5"; ctx.arc(400,300,250,0,360,false); ctx.closePath(); ctx.stroke(); drawScale(12,"#9ef1c5",30,0,-255,0,-250,true,true,[10,30]); //画时刻度 drawScale(60,"#9ef1c5",6,0,-240,0,-250,false,true,[5,10]); //画分刻度 drawPointer(false,"#f19ea2",h,30,0,0,0,-120,[-10,-50,10,-50]); //画时针 drawPointer(false,"#9ee2f1",m,6,0,0,0,-180,[-8,-80,8,-80]); //画分针 drawPointer(false,"#d1f19e",s,6,0,0,0,-240,[-5,-100,5,-100]); //画秒针 //位仪表盘的中心填充颜色 ctx.save(); ctx.beginPath(); ctx.fillStyle = "#666"; ctx.arc(400,300,7,0,360,false); ctx.closePath(); ctx.fill(); ctx.restore(); } drawClock(); setInterval(drawClock,1000);