我试水了画了一个时钟,和mdn的例子略有一点不同。i work it by myself!
<!doctype html> <html lang="en"> <head><meta charset="utf-8"> <title>title</title> </head><body onload="draw()"> <canvas id="canvas" width="300" height="300"> </canvas> <script> function init() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.save(); ctx.clearrect(0,0,300,300); ctx.translate(150,150); ctx.linewidth = 4; ctx.strokestyle = #a77; ctx.beginpath(); ctx.arc(0,0,100,0,math.pi*2,true); ctx.stroke(); ctx.rotate(-math.pi/2);//minute mark ctx.save();for(var i = 0;i<60;i++){if(i%5 != 0){ ctx.beginpath(); ctx.moveto(90,0); ctx.lineto(94,0); ctx.stroke(); } ctx.rotate(math.pi/30); } ctx.restore();//hour mark ctx.save();for(var i=1;i<=12;i++){ ctx.beginpath(); ctx.moveto(85,0); ctx.lineto(95,0); ctx.stroke(); ctx.rotate(math.pi/6); } ctx.restore(); window.requestanimationframe(clock); }function clock() {var ctx = document.getelementbyid('canvas').getcontext('2d');var now = new date();var sec = now.getseconds();var min = now.getminutes();var hr = now.gethours(); hr = hr>=12 ? hr-12 : hr; ctx.beginpath(); ctx.arc(0,0,82,0,math.pi*2,false); ctx.clip(); ctx.clearrect(-90,-90,180,180);//write hour ctx.save(); ctx.linewidth = 6; ctx.rotate(hr*math.pi/6 + min*math.pi/360 + sec*math.pi/21600); ctx.beginpath(); ctx.moveto(0,0); ctx.lineto(50,0); ctx.stroke(); ctx.restore();//write minute ctx.save(); ctx.linewidth = 3; ctx.rotate(min*math.pi/30 + sec*math.pi/1800); ctx.beginpath(); ctx.moveto(0,0); ctx.lineto(65,0); ctx.stroke(); ctx.restore();//write second ctx.save(); ctx.linewidth = 1; ctx.rotate(sec*math.pi/30); ctx.beginpath(); ctx.moveto(0,0); ctx.lineto(80,0); ctx.stroke(); ctx.restore(); window.requestanimationframe(clock); } init(); </script> </body> </html>
view code
这里给出mdn的例子页:点我点我
和mdn的例子不同的是,mdn每次都要重绘整个时钟,而我的做法则将时钟表盘和3个指针分离开来,只需重绘指针。
我觉得这里有两个难点:一个是计算时分针的角度(分针走的同时,时针也会走一些角度)。一个是重绘指针的区域。
canvasrendingcontext2d.rotate(angle)
这里math.pi是半圆,半圆有6个小时,所以math.pi/6是一个小时时针所走的弧度。
因为分针转完一圈,时针就走完1/12圈,所以计算时针对于minute所走的弧度可以这么计算:math.pi*2/60*12 =>math.pi/360
秒针同理。
第二,重绘指针。
若不重绘指针,1分钟之后,你将得到满是360度秒针的时钟。像这样:
那么如何才能重绘指针部分的区域呢?
我想到了裁剪。然后在裁剪的区域重绘。
这样就ok了!(啦啦啦啦啦,手舞足蹈啦啦啦啦~~~)
以上就是canvas画动画时钟的实例代码的详细内容。
