效果:使用html5的canvas和js来实现时钟效果
来源:www.aspbc.com
原创文章,转载请注明来源asp编程网,谢谢
<canvas id="mycanvas" width="600" height="500" style="border: 1px solid #ccc; margin-top: 50px; margin-left: 300px;"></canvas>
<script>
clock();
run(); //加载页面时启动定时器
var interval; //定义一个定时器
function run() {
interval = setInterval(clock, "1000"); //定时的设置
}
function clock(){
x0 = 300;
y0 = 200; //表位置
r = 150; //表半径
var mycanvas = document.getElementById('mycanvas');
var t = mycanvas.getContext("2d");
mycanvas.height=mycanvas.height;
//画圆
t.beginPath();
t.strokeStyle = "#f00";
t.arc(x0,y0,r,0,2*Math.PI,true);
t.stroke();
t.closePath();
//画中心点
t.beginPath();
t.arc(x0,y0,8,0,2*Math.PI,true);
t.fillStyle="#f00";
t.fill();
t.closePath();
//画表盘
for(i=0;i<=60;i++){
t.beginPath();
t.strokeStyle="#f00";
if(i % 15 == 0){ //当0,3,6,9时加最粗
w0 = x0 + (r - 15) * Math.cos(i * 6 * Math.PI / 180);
h0 = y0 + (r - 15) * Math.sin(i * 6 * Math.PI / 180);
t.lineWidth = 5;
}else {
if (i % 5 == 0) { //每小时时加粗
w0 = x0 + (r - 10) * Math.cos(i * 6 * Math.PI / 180);
h0 = y0 + (r - 10) * Math.sin(i * 6 * Math.PI / 180);
t.lineWidth = 2;
} else { //其他时间
w0 = x0 + (r - 5) * Math.cos(i * 6 * Math.PI / 180);
h0 = y0 + (r - 5) * Math.sin(i * 6 * Math.PI / 180);
t.lineWidth = 1;
}
}
t.moveTo(w0,h0);
w1 = x0 + r * Math.cos(i*6*Math.PI/180);
h1 = y0 + r * Math.sin(i*6*Math.PI/180);
t.lineTo(w1,h1);
t.stroke();
t.closePath();
}
var d = new Date();
h = d.getHours();
m = d.getMinutes();
s = d.getSeconds();
//画时针
t.beginPath();
t.strokeStyle="#f00";
t.moveTo(x0,y0);
t.lineWidth = 8;
t1 = (h/12+m/60/12+s/60/60/12)*360-90;
w1 = x0 + 50*Math.cos(t1*Math.PI/180);
h1 = y0 + 50*Math.sin(t1*Math.PI/180);
t.lineTo(w1,h1);
t.stroke();
t.closePath();
//画分针
t.beginPath();
t.strokeStyle="#f00";
t.moveTo(x0,y0);
t.lineWidth = 5;
t1 = (m/60+s/60/60)*360-90;
w1 = x0 + 80*Math.cos(t1*Math.PI/180);
h1 = y0 + 80*Math.sin(t1*Math.PI/180);
t.lineTo(w1,h1);
t.stroke();
t.closePath();
//画秒针
t.beginPath();
t.strokeStyle="#f00";
t.moveTo(x0,y0);
t.lineWidth = 1;
t1 = (s/60)*360-90;
w1 = x0 + 120*Math.cos(t1*Math.PI/180);
h1 = y0 + 120*Math.sin(t1*Math.PI/180);
t.lineTo(w1,h1);
t.stroke();
t.closePath();
}
</script>