HTML5实现可缩放时钟代码
程序员文章站
2023-11-20 17:09:16
本文通过实例代码给大家介绍了基于html5实现的可缩放时钟代码,非常不错,具有参考借鉴价值,需要的的朋友参考下吧... 17-08-28...
废话不多说了,直接给大家贴代码了,具体代码如下所示:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>canvas_time</title> <style type="text/css"> div { text-align: center; margin-top: 250px; } #clock { border: 1px solid #cccccc; } </style> </head> <body> <div> <canvas id="clock" height="600px" width="600px"></canvas> </div> <script type="text/javascript" > var dom = document.getelementbyid('clock'); var ctx = dom.getcontext('2d'); var width = ctx.canvas.width; var height = ctx.canvas.height; var r = width / 2; var rem = width/200; function drawbackground() { ctx.save(); //存储当前环境变量; ctx.translate(r, r); //重置坐标到r,r ctx.beginpath(); // 起始一条路径 ctx.linewidth = 10*rem; //设置线宽10; ctx.arc(0, 0, r - ctx.linewidth /2, 0, 2 * math.pi, false); ctx.stroke(); var hournumbers = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]; //定义数组 ctx.font = 18*rem+"px arial"; ctx.textalign = "center"; ctx.textbaseline = "middle"; hournumbers.foreach(function(number, i) { var rad = 2 * math.pi / 12 * i; var x = math.cos(rad) * (r - 30*rem); var y = math.sin(rad) * (r - 30*rem); ctx.filltext(number, x, y); }); for (var i = 0; i < 60; i++) { var rad = 2 * math.pi / 60 * i; var x = math.cos(rad) * (r - 18*rem); var y = math.sin(rad) * (r - 18*rem); ctx.beginpath(); if (i % 5 === 0) { ctx.arc(x, y, 2*rem, 0, 2 * math.pi, false); ctx.fillstyle = "#000"; } else { ctx.arc(x, y, 2*rem, 0, 2 * math.pi, false); ctx.fillstyle = "#ccc"; } ctx.fill(); } } function drawhour(hour, minute) { ctx.save(); ctx.beginpath(); var rad = 2 * math.pi / 12 * hour; var mrad = 2 * math.pi / 12 / 60 * minute; ctx.rotate(rad + mrad); ctx.linewidth = 6*rem; ctx.linecap = "round"; ctx.moveto(0, 10*rem); ctx.lineto(0, -r / 2); ctx.stroke(); ctx.restore(); } function drawminute(minute) { ctx.save(); ctx.beginpath(); var rad = 2 * math.pi / 60 * minute; ctx.rotate(rad); ctx.linewidth = 3*rem; ctx.linecap = "round"; ctx.moveto(0, 10*rem); ctx.lineto(0, -r + 30*rem); ctx.stroke(); ctx.restore(); } function drawsecond(second) { ctx.save(); ctx.beginpath(); ctx.fillstyle = 'red'; var rad = 2 * math.pi / 60 * second; ctx.rotate(rad); ctx.moveto(-2*rem, 20*rem); ctx.lineto(2*rem, 20*rem); ctx.lineto(1, -r + 16*rem); ctx.lineto(-1, -r + 16*rem); ctx.fill(); ctx.restore(); } function drawdot() { ctx.beginpath(); ctx.fillstyle = '#fff'; ctx.arc(0, 0, 3*rem, 0, 2 * math.pi, false); ctx.fill(); } function draw01() { ctx.clearrect(0, 0, width, height); var now = new date(); var hour = now.gethours(); var minute = now.getminutes(); var second = now.getseconds(); drawbackground(); drawhour(hour, minute); drawminute(minute); drawsecond(second); drawdot(); ctx.restore(); } draw01(); setinterval(draw01, 1000); </script> </body> </html>
总结
以上所述是小编给大家介绍的html5实现可缩放时钟代码,希望对大家有所帮助
上一篇: HTML5中的拖放实现详解