< ! doctype html >
< html >
< head > < / head >
< body >
< canvas width="500" height="500" id="canvas" >
还在用低级浏览器吗?赶紧换了吧,亲。
< / canvas >
< script >
var canvas=document.getElementByIdx_x("canvas");
var cxt=canvas.getContext("2d");
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.beginPath();
cxt.lineWidth=5;
cxt.strokeStyle="blue";
cxt.arc(200,200,150,0,360,false);
cxt.stroke();
cxt.closePath();
//画刻度
//画时钟刻度
for(var i=0;i<12;i++){
cxt.beginPath();
cxt.save();
cxt.translate(200,200);
cxt.rotate(i*30*Math.PI/180);
cxt.lineWidth=5;
cxt.strokeStyle="black";
cxt.moveTo(0,-145);
cxt.lineTo(0,-125);
cxt.stroke();
cxt.closePath();
cxt.restore();
}
//画分钟刻度
for(var i=0;i<12*5;i++){
cxt.save();
cxt.translate(200,200);
cxt.rotate(i*6*Math.PI/180);
cxt.beginPath();
cxt.lineWidth=3;
cxt.strokeStyle="black";
cxt.moveTo(0,-145);
cxt.lineTo(0,-135);
cxt.stroke();
cxt.closePath();
cxt.restore();
}
//画时钟
cxt.save();
cxt.translate(200,200);
cxt.rotate(hour*30*Math.PI/180);
cxt.beginPath();
cxt.lineWidth=8;
cxt.strokeStyle="black";
cxt.moveTo(0,15);
cxt.lineTo(0,-80);
cxt.closePath();
cxt.stroke();
cxt.restore();
//画分钟
cxt.save();
cxt.translate(200,200);
cxt.rotate(min*6*Math.PI/180);
cxt.beginPath();
cxt.lineWidth=5;
cxt.strokeStyle="black";
cxt.moveTo(0,15);
cxt.lineTo(0,-110);
cxt.closePath();
cxt.stroke();
cxt.restore();
//画秒钟
cxt.save();
cxt.translate(200,200);
cxt.rotate(sec*6*Math.PI/180);
cxt.beginPath();
cxt.lineWidth=3;
cxt.strokeStyle="red";
cxt.moveTo(0,15);
cxt.lineTo(0,-130);
cxt.closePath();
cxt.stroke();
//画出交叉点
cxt.beginPath();
cxt.arc(0,0,5,0,360,false);
cxt.closePath();
cxt.fillStyle="black";
cxt.fill();
cxt.stroke();
cxt.restore();
}
drawClock();
setInterval(drawClock,1000);
< / script >
< / body >
< / html >
这个是我看了实例模仿写的。嘿嘿。编写过程中,最重要的就是那个2次元的(0,0)点对于和它相对应的坐标,经常会搞错,然后就画不出相应的线段。其中:hour=hour>12?hour-12:hour;的意思是:前面判断是就执行:前面的,否就执行:后面的。