canvas之动态时间
<!DOCTYPE HTML>
<html>
<head>
<title>Html5 Canvas Animations 3</title>
</head>
<body onload="init()" >
<canvas id="c" width="400" height="200"></canvas>
<script type="text/javascript">
var ctx;
function init(){
ctx = document.getElementById('c').getContext('2d');
setInterval(draw,1000);
}
function draw(){
ctx.clearRect(0,0,400,200);
var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
sec = sec < 10 ? '0'+sec : sec;
min = min < 10 ? '0'+min : min;
hr = hr < 10 ? '0'+hr : hr;
sec = new String(sec);
min = new String(min);
hr = new String(hr);
//hr
showNumber(hr.substr(0,1),50,50);
showNumber(hr.substr(1,1),100,50);
showNumber('.',160,70);
showNumber('.',160,90);
//min
showNumber(min.substr(0,1),170,50);
showNumber(min.substr(1,1),220,50);
showNumber('.',280,70);
showNumber('.',280,90);
//sec
showNumber(sec.substr(0,1),290,50);
showNumber(sec.substr(1,1),340,50);
}
function showNumber(n,x,y){
var img = new Image();
img.src = 'images/numbers.jpg';
switch (n)
{
case '.':
ctx.drawImage(img,69,54,10,10,x,y,10,10);
break;
case '1':
ctx.drawImage(img,0,0,110,174,x,y,50,60);
break;
case '2':
ctx.drawImage(img,110,0,110,174,x,y,50,60);
break;
case '3':
ctx.drawImage(img,220,0,110,174,x,y,50,60);
break;
case '4':
ctx.drawImage(img,330,0,110,174,x,y,50,60);
break;
case '5':
ctx.drawImage(img,450,0,110,174,x,y,50,60);
break;
case '6':
ctx.drawImage(img,0,174,120,174,x,y,50,60);
break;
case '7':
ctx.drawImage(img,120,174,110,174,x,y,50,60);
break;
case '8':
ctx.drawImage(img,230,174,110,174,x,y,50,60);
break;
case '9':
ctx.drawImage(img,340,174,110,174,x,y,50,60);
break;
default:
ctx.drawImage(img,460,174,120,174,x,y,59,60);
}
}
</script>
</body>
</html>