用H5绘制一个模拟时钟,效果图:
html
<canvas id="clock" width="500px" height="500px" style="background-color:#fff">您的浏览器版本不支持!</canvas>
javascript
<script>
var clock=document.getElementById("clock");
var cxt=clock.getContext('2d');
/**数字时钟**/
function time(){
var now=new Date();
var hour=now.getHours();
var min=now.getMinutes();
var sec=now.getSeconds();
hour=checkTime(hour);
min=checkTime(min);
sec=checkTime(sec);
cxt.font="normal 20px arial"
cxt.fillStyle='#00f';
cxt.fillText("北京时间:"+hour+":"+min+":"+sec,50,430);
/*t=setTimeout('time()',500);*/
}
function checkTime(i){
if(i<10){
i="0"+i;
}
return i;
}
/**模拟时钟**/
function drawClock(){
cxt.clearRect(0,0,500,500);
var now=new Date();
var hour=now.getHours();
var min=now.getMinutes();
var sec=now.getSeconds();
hour=hour+min/60;
hour=hour>12?hour-12:hour;
//绘文字
cxt.font="normal 20px arial"
cxt.fillStyle='#00f';
cxt.fillText('Canvas绘制模拟时钟......',50,50);
//表盘
cxt.lineWidth=5;
cxt.strokeStyle="blue";
cxt.beginPath();
cxt.arc(250,250,95,0,360,false);
cxt.closePath();
cxt.stroke();
//刻度
//时刻
for(var i=0;i<12;i++){
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(i*30*Math.PI/180);//角度*math.PI/180=弧度
cxt.beginPath();
cxt.moveTo(0,-80);
cxt.lineTo(0,-90);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//分刻
for(var i=0;i<60;i++){
cxt.save();
cxt.lineWidth=2;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(i*6*Math.PI/180);//角度*math.PI/180=弧度
cxt.beginPath();
cxt.moveTo(0,-85);
cxt.lineTo(0,-90);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//时针
cxt.save();
cxt.lineWidth=4;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(hour*30*Math.PI/180);//角度*math.PI/180=弧度
cxt.beginPath();
cxt.moveTo(0,-60);
cxt.lineTo(0,10);
cxt.closePath();
cxt.stroke();
cxt.restore();
//分针
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(min*6*Math.PI/180);//角度*math.PI/180=弧度
cxt.beginPath();
cxt.moveTo(0,-70);
cxt.lineTo(0,12);
cxt.closePath();
cxt.stroke();
cxt.restore();
//秒针
cxt.save();
cxt.lineWidth=2;
cxt.strokeStyle="#f00";
cxt.translate(250,250);
cxt.rotate(sec*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-80);
cxt.lineTo(0,15);
cxt.closePath();
cxt.stroke();
//秒针美化
cxt.beginPath();
cxt.arc(0,0,3,0,360,false);
cxt.closePath();
cxt.fillStyle="black";
cxt.fill();
cxt.stroke();
//秒针美化
cxt.beginPath();
cxt.arc(0,-65,2,0,360,false);
cxt.closePath();
cxt.fillStyle="black";
cxt.fill();
cxt.stroke();
cxt.restore();
}
/**设置模拟时钟触发时间,1000毫秒触发一次。setInterval(函数,1000);**/
drawClock();
setInterval(drawClock,1000);
/**设置数字时钟触发时间,1000毫秒触发一次。setInterval(函数,1000);**/
time();
setInterval(time,1000);
</script>