<!DOCTYPE html>
<html>
<head>
<title>Canvas clock</title>
<style type="text/css">
#myclock{
border:1px solid red;
}
#div01{
width:400;
height:400;
border:1px solid blue;
}
</style>
</head>
<body>
<div id="div01">
<canvas id="myclock" width="200" height="200" ></canvas>
</div>
<script type="text/javascript">
var drawing = document.getElementById("myclock");
var width = drawing.width;
var height = drawing.height;
var r = width/2;
if(drawing.getContext){//确定浏览器元素支持Canvas元素
var context = drawing.getContext("2d");
//画背景
function drawBackground(){
context.save();
context.translate(r,r);//将起始点投射到中心
context.beginPath();
context.lineWidth = 10;
context.arc(0,0,r-10,0,2*Math.PI,false);//绘制外圆
context.stroke();
//绘制时间数
var hoursNumber = [3,4,5,6,7,8,9,10,11,12,1,2];
context.font = "18px Arial";
context.textAlign = "center";
context.textBaseline = "middle";
hoursNumber.forEach(function(number,i){//数组迭代forEach(function(item,index,array){});
var rad = 2*Math.PI/12*i;
var x = Math.cos(rad)*(r-30);
var y = Math.sin(rad)*(r-30);
context.fillText(number,x,y);
});
for(var i=0;i<60;i++){
var rad = 2*Math.PI/60*i;
var x = Math.cos(rad)*(r-20);
var y = Math.sin(rad)*(r-20);
context.beginPath();
if(i%5 === 0){
context.fillStyle = "black";
context.arc(x,y,2,0,2*Math.PI,false);
}else{
context.fillStyle = "#ccc";
context.arc(x,y,2,0,2*Math.PI,false);
}
context.fill();
}
}
//画时针
function drawHour(hour,minute){
context.save();
context.lineWidth = 6;
context.lineCap = "round";
context.beginPath();
context.moveTo(0,10);
var rad = 2*Math.PI/12*hour;
var minute_rad = 2*Math.PI/12/60*minute;
context.rotate(rad+minute_rad);//以rad弧度旋转当前绘图
//context.lineTo(Math.cos(2*Math.PI/12*(hour-3))*(r-50),Math.sin(2*Math.PI/12*(hour-3))*(r-50));
context.lineTo(0,-r/2);
context.stroke();
context.restore();
}
//画分针
function drawMinute(minute){
context.save();
context.lineWidth = 3;
context.lineCap = "round";
context.beginPath();
context.moveTo(0,10);
var rad = 2*Math.PI/60*minute;
context.rotate(rad);//以rad弧度旋转当前绘图
//context.lineTo(Math.cos(2*Math.PI/12*(hour-3))*(r-50),Math.sin(2*Math.PI/12*(hour-3))*(r-50));
context.lineTo(0,-r+30);
context.stroke();
context.restore();
}
//画秒针
function drawSecond(second){
context.save();
context.lineWidth = 2;
context.lineCap = "round";
context.fillStyle = "red";
context.beginPath();
var rad = 2*Math.PI/60*second;
context.rotate(rad);//以rad弧度旋转当前绘图
context.moveTo(-2,20);
context.lineTo(2,20);
context.lineTo(1,-r+18);
context.lineTo(-1,-r+18);
context.fill();
context.restore();
}
//画转轴
function drawDot(){
context.beginPath();
context.arc(0,0,5,0,2*Math.PI,false)
context.fillStyle = "white";
context.fill();
}
function draw(){
context.clearRect(0,0,width,width);
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
drawBackground();
drawHour(hour/2,minute);
drawMinute(minute);
drawSecond(second);
drawDot();
context.restore();
}
}
setInterval(draw,1000);
</script>
</body>
</html>