先上图
function Clock(options){
this.config = {target : "",
width:500,
height:500
}
for(var key in options){
this.config[key] = options[key];
}
this.init();
}
Clock.prototype = {
//时钟初始化
init : function(){
var canvas = document.querySelector(this.config.target);
canvas.width = this.config.width ;
canvas.height = this.config.height ;
this.context = canvas.getContext("2d") ;
this.context.translate( this.config.width/2 , this.config.height/2 );
//将表盘的绘制起点移到画布的中心,因此下文的画圆的起点可以从零开始 ,这是一个坑!!!
this.rotate();
},
//表盘的绘制
dial : function(h,m,s){
var context = this.context ;
//半径取长度和宽度最小值,防止钟盘绘制超出画布区域
this.r = this.config.width > this.config.height ? this.config.height / 2 - 30 : this.config.width / 2 - 30 ;
context.save();
context.beginPath();
context.fillStyle = "#E4EDF6" ;
context.strokeStyle = "#C9DCEE" ;
context.arc(0,0,this.r,0,Math.PI*2);
context.fill();
context.stroke() ;
context.restore();
context.closePath();
this.mark();
this.num() ;
this.needle("h",h);
this.needle("m",m);
this.needle("s",s);
},
//刻度的绘制
mark : function(){
var context = this.context ;
context.save() ;
context.fillStyle = "#68CFA9" ;
var deg = Math.PI/ 30 ; //每个格子的度数
for(var i=0 ; i<60 ; i++){
context.beginPath() ;
if( i%5==0 ){
context.rect(0,-this.r+5,5,10); //绘制矩形
}else{
context.arc(0,-this.r+8,3,0,2*Math.PI); //绘制圆形
}
context.rotate( deg ) ; //每格旋转度数为Math.PI/30
context.fill();
}
context.closePath();
context.restore() ;
},
num : function(){
var context = this.context ;
var deg = Math.PI*2 / 12 ;
context.save();
context.beginPath();
for(var i=1 ;i<13 ; i++){
var x1 = Math.sin(i*deg) ;
var y1 = -Math.cos(i*deg) ;
context.font = "bold 24px Calibri"
context.fillText(i,x1*188,y1*188 );
}
context.closePath();
context.restore();
},
//绘制指针
needle : function( needle_type , time ){
var deg = Math.PI / 30 ;
var degH = 2*Math.PI / 12 ;
var context = this.context;
context.save();
context.beginPath();
switch(needle_type){
case "h" :
context.fillStyle = "#142D3D" ;
context.rotate( degH*time ) ;
context.rect(0,-this.r/1.8,6,this.r/1.5) ;
break;
case "m" :
context.fillStyle = "#6D62CB" ;
context.rotate( deg*time ) ;
context.rect(0,-this.r/1.8,4,this.r/1.4) ;
break;
case "s" :
context.fillStyle = "#C35B4B" ;
context.rotate( deg*time ) ;
context.rect(0,-this.r/1.4,2,this.r/1.2) ;
break;
}
context.fill();
context.closePath();
context.restore();
},
rotate : function(){
var context = this.context ;
var _this = this ;
function time(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
if(h>12){
h = h - 12 ;
}
context.clearRect( 0,0,_this.config.width,_this.config.height );
_this.dial(h,m,s);
}
setInterval(time,1000) ;
}
}
//实例化Clock
new Clock({
target:"canvas",//canvas的id
width:500,//设置画布的宽
height:500//设置画布的高
});