用HTML5 Canvas写了个时钟
这周在学canvas,就写了个时钟练习练习
window.onload = function(){var Timer = function(canvas_id){this.canvas = document.getElementById(canvas_id);this.ctx = this.canvas.getContext('2d');this.width = this.canvas.width;this.height = this.canvas.height;};Timer.prototype = {draw:function(){this.ctx.save();this.ctx.translate(0,0);this.ctx.clearRect(0,0,this.width,this.height);this.drawBackground();this.drawClock();this.drawClockPoint();this.ctx.restore(); },drawBackground:function(){this.ctx.globalAlpha = 0.5;this.ctx.fillStyle = 'blue';this.ctx.fillRect(0,0,this.width,this.height);},drawClock:function(){//move to centerthis.ctx.translate(this.width/2,this.height/2);//inner arc// this.ctx.fillStyle = '#333333';this.ctx.beginPath();this.ctx.arc(0,0,(this.width)/20,0,Math.PI*2,true);this.ctx.fill();// //outer arcthis.ctx.fillStyle = 'yellow';this.ctx.beginPath();this.ctx.arc(0,0,(this.width/2),0,Math.PI*2,true);this.ctx.fill();// Outer arc linefor(var i=0;i<60;i++){this.ctx.save();this.ctx.rotate(Math.PI*2/60*i)this.ctx.beginPath();if(i % 5 == 0){this.ctx.moveTo((this.width/2.5),0);}else{this.ctx.moveTo((this.width/2.2),0);}this.ctx.lineTo(this.width/2,0)this.ctx.stroke();this.ctx.restore();}},drawClockPoint:function(){var currentDate = new Date();var hour = currentDate.getHours();var minute = currentDate.getMinutes();var second = currentDate.getSeconds();// alert(second);//画秒钟this.ctx.save();// this.ctx.fillStyle = 'black';this.ctx.rotate(Math.PI*2/60*second - Math.PI/2)this.ctx.beginPath();this.ctx.moveTo(0,0);this.ctx.lineTo(this.width/2,0);this.ctx.stroke(); this.ctx.restore(); //画分钟this.ctx.save();// this.ctx.lineWidth=5;this.ctx.fillStyle = 'black';this.ctx.rotate(Math.PI*2/60*(minute+second/60) - Math.PI/2)this.ctx.beginPath();this.ctx.moveTo(0,0);this.ctx.lineTo(this.width/3,0);this.ctx.stroke(); this.ctx.restore(); //画时钟this.ctx.save();// this.ctx.lineWidth=10;this.ctx.fillStyle = 'black';this.ctx.rotate(Math.PI*2/12*(hour+minute/60+second/3600) - Math.PI/2)this.ctx.beginPath();this.ctx.moveTo(0,0);this.ctx.lineTo(this.width/3.5,0);this.ctx.stroke(); this.ctx.restore(); }}; var timer = new Timer('canvas'); timer.draw(); function run (){ timer.draw(); } window.setInterval(run,1000); }
?页面代码
很短到一句
<canvas id='canvas' width='200' height='200'></canvas>
?
?
?
?
?