Canvas绘制的简单模拟时钟
2012-01-17 17:09
357 查看
下午碰到这个问题,刚开始懵了,理一下思路,很简单的事情。
function getDegree(hour,minute){ var degree=0; var _m=6*minute; var _h=30*hour+_m/12; degree=_m-_h; return degree; }
顺着这个想法,使用canvas来绘制一个简单的钟表
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Clock</title> </head> <body> <canvas id="canvas" width="400" height="400"></canvas> <script type="text/javascript" src="line.js"></script> <script type="text/javascript"> window.onload=function(){ var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); var secondHand=new Line(50,1,'#ff0000'); var minuteHand=new Line(40,2,'#000000'); var hourHand=new Line(25,3,'#000000'); secondHand.x=minuteHand.x=hourHand.x=canvas.width/2; secondHand.y=minuteHand.y=hourHand.y=canvas.height/2; var count=0; (function animationLoop(){ window.requestAnimationFrame(animationLoop,canvas); if(count===60){ count=0; var now=new Date(); var second=now.getSeconds(); secondHand.rotation=(second*6-90)*Math.PI/180; var minute=now.getMinutes(); minuteHand.rotation=(minute*6-90)*Math.PI/180+secondHand.rotation/60; var hour=now.getHours()%12; hourHand.rotation=(hour*30-90)*Math.PI/180+minuteHand.rotation/12; context.clearRect(0,0,canvas.width,canvas.height); context.beginPath(); context.arc(canvas.width/2,canvas.height/2,60,0,Math.PI*2,true); context.closePath(); context.stroke(); secondHand.paint(context); minuteHand.paint(context); hourHand.paint(context); }else{ count++; } })(); }; </script> </body> </html>
下面是画线的函数
function Line(width,height,color){ this.x=0; this.y=0; this.width=width||100; this.height=height||1; this.color=color||'#ff0000'; this.rotation=0; } Line.prototype.paint=function(context){ context.save(); context.translate(this.x,this.y); context.rotate(this.rotation); context.strokeStyle=this.color; context.lineWidth=this.height; context.beginPath(); context.moveTo(0,0); context.lineTo(this.width,0); context.closePath(); context.stroke(); context.restore(); };
阅读更多
相关文章推荐
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- 利用canvas绘制一个简单时钟
- 学者玩玩Canvas-写个简单的模拟时钟
- html5使用canvas标签绘制简单的时钟
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- android 用canvas 绘制简单圆形时钟
- WinForm学习 --简单的模拟时钟程序
- Canvas绘制时钟(学习笔记)
- 【Android Canvas系列】使用canvas绘制简单的clock
- 【一天一个canvas】绘制一个简单的矩形框(四)
- canvas自适应圆形时钟绘制
- 使用canvas绘制一个时钟
- Html5 Canvas 绘制 时钟
- js+canvas简单绘制圆圈的方法