canvas如何绘制钟表的方法
程序员文章站
2023-11-20 16:53:52
这篇文章主要介绍了canvas如何绘制钟表的方法的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧... 17-12-13...
本文介绍了canvas如何绘制钟表的方法,分享给大家,具体如下:
效果图为
上代码:
var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var year,month,day,hour,second,minute; // 绘制表盘 function drawclockpie(){ ctx.beginpath(); ctx.linewidth = 2; ctx.strokestyle = '#333'; ctx.arc(150,150,146,0,2*math.pi); ctx.stroke(); ctx.closepath(); ctx.beginpath(); ctx.arc(150,150,6,0,2*math.pi); ctx.fillstyle = 'red'; ctx.fill(); ctx.closepath(); } // 绘制时刻度 function drawclockhours(){ for(var i = 0,l = 12; i < 12; i++){ ctx.save(); ctx.translate(150,150); ctx.rotate(i*1/12*2*math.pi); ctx.beginpath(); ctx.linewidth = 5; ctx.strokestyle = '#333'; ctx.moveto(0,-140); ctx.lineto(0,-125); ctx.stroke(); ctx.closepath(); ctx.restore(); } } // 绘制分刻度 function drawclockmins(){ for(var i = 0,l = 60; i < 60; i++){ ctx.save(); ctx.translate(150,150); ctx.rotate(i*1/60*2*math.pi); ctx.beginpath(); ctx.linewidth = 3; ctx.strokestyle = '#333'; ctx.moveto(0,-140); ctx.lineto(0,-133); ctx.stroke(); ctx.closepath(); ctx.restore(); } } // 绘制时针 function drawhourpin(){ ctx.save(); ctx.translate(150,150); ctx.rotate((hour*60*60+minute*60+second)/(12*60*60)*2*math.pi); ctx.beginpath(); ctx.strokestyle = '#333'; ctx.linewidth = 3; ctx.moveto(0,0); ctx.lineto(0,-40); ctx.stroke(); ctx.closepath(); ctx.restore(); } // 绘制分针 function drawminpin(){ ctx.save(); ctx.translate(150,150); ctx.rotate((minute*60+second)/(60*60)*2*math.pi); ctx.beginpath(); ctx.strokestyle = '#333'; ctx.linewidth = 2; ctx.moveto(0,0); ctx.lineto(0,-60); ctx.stroke(); ctx.closepath(); ctx.restore(); } // 绘制秒针 function drawsecpin(){ ctx.save(); ctx.translate(150,150); ctx.rotate(second/60*2*math.pi); ctx.beginpath(); ctx.strokestyle = 'red'; ctx.linewidth = 1; ctx.moveto(0,0); ctx.lineto(0,-80); ctx.stroke(); ctx.closepath(); ctx.restore(); } // 绘制时间文字 function drawtext(){ hour = hour >= 12 ? hour - 12 : hour; var time = '现在是' + year + '年' + month + '月' + day + '日' + hour + '时' + minute + '分' + second + '秒'; ctx.font = '15px 黑体'; ctx.filltext(time,24,350); } // 获取时间 function gettimes(){ var date = new date(); year = date.getfullyear(); month = date.getmonth() + 1; day = date.getdate(); hour = date.gethours(); minute = date.getminutes(); second = date.getseconds(); } setinterval(function(){ ctx.clearrect(0,0,600,600); drawclockpie(); drawclockhours(); drawclockmins(); gettimes(); drawtext(); drawhourpin(); drawminpin(); drawsecpin(); },1000);
注:
当然时间也可以不用这样每隔一秒就获取,直接获取一次按秒递增就行。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Html5百叶窗效果的示例代码
下一篇: canvas如何绘制钟表的方法