效果图:
canvas代码:
<body>
<canvas id="clock" width="500" height="500">
您的破浏览器不支持canvas标签。
</canvas>
</body>
javascript代码:
<script>
var clock=document.getElementById('clock');
var cxt=clock.getContext('2d');
function drawClock(){
cxt.clearRect(0,0,500,500); //清除画布
var now=new Date();
var second=now.getSeconds();
var minute=now.getMinutes();
var hour=now.getHours();
hour=hour+minute/60; //使小时刻度更加精确
//将24小时进制转化为12小时制。
hour=hour>12?hour-12:12;
//表盘(蓝色)
cxt.lineWidth=10;
cxt.strokeStyle="ABCDEF";
cxt.beginPath();
cxt.arc(250,250,200,0,360,false);
cxt.closePath();
cxt.stroke();
//刻度
for(var i=0;i<12;i++){ //时刻
cxt.save(); //使用虚拟画布
cxt.lineWidth=7; //设置时针的粗细
cxt.strokeStyle="#000";//设置颜色
cxt.translate(250,250) //设置旋转点。
cxt.rotate(i*30*Math.PI/180); //设置旋转角度。角度*Math.PI=弧度。
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,-190);
cxt.stroke();
cxt.restore(); //结束虚拟画布
}
for(var i=0;i<60;i++){ //分刻度
cxt.save(); //使用虚拟画布
cxt.lineWidth=5;
cxt.translate(250,250); //设置旋转点。
cxt.rotate(i*6*Math.PI/180); //设置旋转角度。角度*Math.PI=弧度。
cxt.beginPath();
cxt.moveTo(0,-180);
cxt.lineTo(0,-190);
cxt.stroke();
cxt.closePath();
cxt.restore(); //结束虚拟画布
}
cxt.save(); //画时刻针
cxt.lineWidth=7;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(hour*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-140);
cxt.lineTo(0,10);
cxt.stroke();
cxt.closePath();
cxt.restore();
cxt.save();//画分刻针
cxt.lineWidth=5;
cxt.strokeStyle="#000";
cxt.translate(250,250);
// cxt.rotate(180*Math.PI/180);
cxt.rotate(minute*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-160);
cxt.lineTo(0,15);
cxt.closePath();
cxt.stroke();
cxt.restore();
cxt.save()//画秒刻针
cxt.lineWidth=2;
cxt.strokeStyle="red";
cxt.translate(250,250);
//cxt.rotate(330*Math.PI/180);
cxt.rotate(second*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,19);
cxt.closePath();
cxt.stroke();
cxt.beginPath(); //画圆心的红色圆圈点。
cxt.arc(0,0,5,0,360,false);
cxt.fillStyle="gray";
cxt.fill();
cxt.closePath();
cxt.stroke();
cxt.beginPath(); //画秒钟中的红色圆圈点。
cxt.arc(0,-150,5,0,360,false);
cxt.fillStyle="gray";
cxt.fill();
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//使用setInterval(代码,毫秒)让时钟动起来。
drawClock();
setInterval(drawClock,1000);
</script>