<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas test</title>
</head>
<body>
<div class="wrap">
<canvas id="canvas" width="400px" height="300px" style="border: 1px solid red;">
</canvas>
</div>
<script type="text/javascript">
window.onload = draw;
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var deg=2*Math.PI/12;
var context = canvas.getContext("2d");
context.clearRect(0,0,400,400)
context.save();
context.beginPath();
context.arc(140, 140, 130, 0, 2 * Math.PI, true);
context.stroke();
context.closePath();
context.beginPath();
context.arc(140, 140, 125, 0, 2 * Math.PI, true);
context.stroke();
context.closePath();
context.save();
context.translate(140,140)
context.beginPath();
for(var i=1;i<13;i++){
var x1=Math.sin(i*deg);
var y1=-Math.cos(i*deg);
context.fillStyle="#000";
context.font="bold 20px Calibri";
context.textAlign='center';
context.textBaseline='middle';
context.fillText(i,x1*110,y1*110);
}
context.stroke();
context.closePath();
context.restore();
context.save();
context.translate(140,140)
var deg1=2*Math.PI/60;
context.beginPath();
for(var i=0;i<60;i++){
var x2=Math.sin(i*deg1);
var y2=-Math.cos(i*deg1);
context.moveTo(x2*123,y2*123);
context.lineTo(x2*120,y2*120);
}
context.strokeStyle='#000';
context.lineWidth=2;
context.stroke();
context.closePath();
context.restore();
context.translate(140,140)
start(context)
setTimeout(draw,1000);
}
}
function start(context){
var date = new Date();
var seconds = date.getSeconds()*2*Math.PI/60;
var minutes = date.getMinutes()*6*Math.PI/180+seconds/60;
var hour =(date.getHours()%12)*0.5*Math.PI/180+minutes/12+seconds/720;
drawLine(context,hour,-48,6);
drawLine(context,minutes,-78,3);
drawLine(context,seconds,-90,1);
context.restore();
context.restore();
}
function drawLine(context,mintues,endpoint,width){
context.save();
context.beginPath();
context.rotate(mintues);
context.moveTo(0,5);
context.lineTo(0,endpoint);
context.strokeStyle="black";
context.lineWidth=width;
context.stroke();
context.closePath();
context.restore();
}
</script>
</body>
</html>
最后效果如下: