时钟
用过js和css写过时钟,现在用canvas写一个时钟,发现canvas写出来的动画比css写出来的效果及性能好,先看看效果
下面就分享一下canvas的时钟代码
html
<canvas id="myCanvas" width="300" height="300"></canvas>
js
var can = document.getElementById('myCanvas'),
width = can.width,
height = can.height,
ctx = can.getContext('2d'),
r = width/2,
now_point = 0;
ctx.translate(r,r);
function circle(){
ctx.save();
ctx.beginPath();
ctx.arc(0,0,r-4,0,Math.PI*2,true);
ctx.lineWidth = 2.0;
ctx.strokeStyle = "#ccc";
ctx.restore();
ctx.stroke();
ctx.closePath();
point();
number();
};
function point(){
for(var i=0;i<60;i++){
var rad = Math.PI * 2/60 * (i+1),
x = (r-14) * Math.sin(rad),
y = -(r-14) * Math.cos(rad);
ctx.save();
ctx.beginPath();
if((i+1)%5 != 0){
ctx.arc(x,y,2,0,Math.PI*2,true);
}
if(i+1 == now_point){
ctx.save();
ctx.fillStyle = "#f90";
ctx.fill();
ctx.restore();
}else{
ctx.save();
ctx.fillStyle = "#ccc";
ctx.fill();
ctx.restore();
}
}
};
function number(){
var arr = ['1','2','3','4','5','6','7','8','9','10','11','12'];
arr.forEach(function(number,i){
ctx.save();
ctx.font = '12px Times New Roman';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle'
var rad = Math.PI * 2/12 * (i+1),
x = (r-14) * Math.sin(rad),
y = -(r-14) * Math.cos(rad);
ctx.strokeText(number, x, y);
ctx.restore();
})
};
function second(sec){
common1();
var rad = Math.PI * 2/60 * sec;
ctx.rotate(rad);
ctx.lineWidth = 1.0;
ctx.strokeStyle = 'red';
ctx.moveTo(0,-16);
ctx.lineTo(0,120);
common2();
}
function minute(min,sec){
common1();
var rad_min = Math.PI * 2/60 * min,
rad_sec = Math.PI * 2/60 * sec/60;
ctx.rotate(rad_min + rad_sec);
ctx.lineWidth = 2.0;
ctx.strokeStyle = 'yellow';
ctx.moveTo(0,-12);
ctx.lineTo(0,100);
common2()
}
function hours(hou,min){
common1();
var rad_hou = Math.PI * 2/12 * hou,
rad_min = Math.PI * 2/12 * min/60;
ctx.rotate(rad_min + rad_hou);
ctx.lineWidth = 4.0;
ctx.strokeStyle = 'green';
ctx.moveTo(0,-8);
ctx.lineTo(0,70);
common2();
}
function common1(){
ctx.save();
ctx.beginPath();
ctx.rotate(180 * Math.PI/180);
}
function common2(){
ctx.stroke();
ctx.restore();
ctx.closePath();
}
function now(){
ctx.clearRect(-r, -r, width, height);
var now_time = new Date(),
sec = now_time.getSeconds(),
min = now_time.getMinutes(),
hou = now_time.getHours();
now_point = sec;
circle();
second(sec);
minute(min,sec);
hours(hou,min);
ctx.arc(0,0,4,0,Math.PI*2,true);
ctx.fillStyle = "blue";
ctx.fill();
ctx.restore();
}
setInterval(now, 1000);