您的浏览器不支持canvas标签,请更换浏览器
var clock=document.getElementById('clock');
var cxt=clock.getContext('2d');
function drawClock(){
//清除画布
cxt.clearRect(0,0,500,500);
var now=new Date();
var sec=now.getSeconds();
var min=now.getMinutes();
var hour=now.getHours();
//小时必须获取浮点型的小时
hour=hour+min/60;
//将24小时进制转换成12小时进制
//18:12:56
hour=hour>12?(hour-12):hour;
//表盘(蓝色)
cxt.lineWidth=10;
cxt.strokeStyle="blue";
cxt.beginPath();
cxt.arc(250,250,200,0,260,false);
cxt.closePath();
cxt.stroke();
//刻度
//时刻度
for(var x=0;x<12;x++){
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="#000";
cxt.translate(250,250);
//再设置角度
cxt.rotate(x*30*Math.PI/180);
//画刻度
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,-190);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//分刻度
for(var x=0;x<60;x++){
cxt.save();
cxt.lineWidth=5;
cxt.strokeStyle="#000";
cxt.translate(250,250);
//再设置角度
cxt.rotate(x*6*Math.PI/180);
//画刻度
cxt.beginPath();
cxt.moveTo(0,-180);
cxt.lineTo(0,-190);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//时针
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="#000";
cxt.translate(250,250);
//再设置角度
cxt.rotate(90*Math.PI/180);
//画刻度
cxt.beginPath();
cxt.moveTo(0,-140);
cxt.lineTo(0,7);
cxt.closePath();
cxt.stroke();
cxt.restore();
//分针
cxt.save();
cxt.lineWidth=5;
cxt.strokeStyle="#000";
cxt.translate(250,250);
//再设置角度
cxt.rotate(min*6*Math.PI/180);
//画刻度
cxt.beginPath();
cxt.moveTo(0,-150);
cxt.lineTo(0,12);
cxt.closePath();
cxt.stroke();
cxt.restore();
//秒针
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="red";
cxt.translate(250,250);
//再设置角度
cxt.rotate(sec*6*Math.PI/180);
//画刻度
cxt.beginPath();
cxt.moveTo(0,-160);
cxt.lineTo(0,15);
cxt.closePath();
cxt.stroke();
//画出 时针、分针和秒针的交叉点
cxt.beginPath();
cxt.arc(0,0,5,0,360,false);
cxt.closePath();
cxt.fillStyle="gray"
cxt.fill();
//画小红圈
cxt.stroke();
//设置秒针前端的小圆点
cxt.beginPath();
cxt.arc(0,-140,5,0,360,false);
cxt.closePath();
cxt.fillStyle="black"
cxt.fill();
//画小红圈
cxt.stroke();
cxt.restore();
}
drawClock();
//周期循环函数 让时针动起来 setInterval
setInterval(drawClock,1000);
window.onload = function() {
var pic = new Image();
pic.src ="poc.jpg";
context2D.drawImage(pic,0, 0);
}