利用HTML5 Canvas實現一個時鐘
本時鐘是通過HTML5的Canvas實現的,相關的技術大家可以到這兒去看看: 鏈接地址
下面就沒有什么好所的了,上面的鏈接中有詳細的說明,有圖有真相 ~~
下面是代碼:
<html>
<head>
<title>HTML5 Test</title>
<script type="application/x-javascript">
var panel, ctx, img;
var pw, ph, ox, oy;
function init(){
panel = document.getElementById("panel");
pw = panel.width;
ph = panel.height;
ox = pw/2;
oy = ph/2;
if(panel.getContext){
ctx = panel.getContext('2d');
}else{
alert('Your browser is not support Canvas tag!');
}
ctx.translate(ox, oy);
img = new Image();
img.onload = function(){
setInterval('draw()',1000);
}
img.src = 'bg.jpg';
}
function drawSecond(){
ctx.save();
ctx.rotate(Math.PI/180*currTime().s*6);
ctx.strokeStyle = "#09f";
ctx.lineWidth = 2;
ctx.lineCap = 'round'
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(0,-140);
ctx.stroke();
ctx.restore();
}
function drawMinute(){
ctx.save();
ctx.rotate(Math.PI/180*currTime().m*6);
ctx.strokeStyle = "#f90";
ctx.lineWidth = 6;
ctx.lineCap = 'round'
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(0,-100);
ctx.stroke();
ctx.restore();
}
function drawHour(){
ctx.save();
ctx.rotate(Math.PI/180*currTime().h*30+Math.PI/180*currTime().m/
2);
ctx.strokeStyle = "#999";
ctx.lineWidth = 10;
ctx.lineCap = 'round'
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(0,-60);
ctx.stroke();
ctx.restore();
}
function draw(){
ctx.clearRect(-pw/2,-ph/2,pw,ph);
drawBackground();
drawSecond();
drawMinute();
drawHour();
document.getElementById('time').innerHTML=currTimeStr();
}
function drawBackground(){
ctx.save();
ctx.translate(0, 0);
ctx.drawImage(img,-250,-250,500,500);
ctx.restore();
}
function currTimeStr(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
return h+':'+m+':'+s
}
function currTime(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(h>12){
h = h-12;
}
return {"h":h,"m":m,"s":s};
}
</script>
</head>
<body onload="init()">
<canvas style="border:1px solid #000" id="panel" width="500" height="500
">
Your browser is not support Canvas tag!
</canvas>
<br/>
<span id="time"></span>
</body>
</html></pre>下面是背景圖片:
