JS html时钟制作代码分享
程序员文章站
2023-11-11 18:19:04
时钟效果图:
闲来无聊做了一个网页的时钟,效果模拟传统时钟的运行方式,
运用了html 的画布实现指针,背景图片引用了网络图片。
具体原理:
首先将时钟分为...
时钟效果图:
闲来无聊做了一个网页的时钟,效果模拟传统时钟的运行方式,
运用了html 的画布实现指针,背景图片引用了网络图片。
具体原理:
首先将时钟分为四个不同区域,对每个区域计算cos,sin 来确实指针顶点位置。在通过画布来绘画出指针。
通过setinterval 每秒刷新指针位置实现 传统机械表针的动态跳动。
本人是js开发程序员,从业1年多。闲来无聊的简单页面,
欢迎大家提问,或者建议。共同进步
代码部分,直接复制html 文件中即可查看效果:
<!doctype html> <html> <head> <meta charset=utf-8> <title>clock</title> </head> <body style="color:green; <!--background-image:url('http://image.lxway.com/upload/b/f0/bf0d97dcee487096548e6edbc89d4963_thumb.png');--> background-size:100%; background-repeat: no-repeat; background-attachment:fixed"> <div style="width: 900px; height: 900px; margin-top: 50px; margin-left: 50px;"> <div style="position: absolute; left:119px;top: 193px; width: 900px; height: 900px; background-image:url('http://image.lxway.com/upload/b/f0/bf0d97dcee487096548e6edbc89d4963_thumb.png'); background-repeat: no-repeat; z-index: -1;"> </div> <canvas id="t" width="800" height="800"></canvas> <div style="position: absolute; left:118px;top: 464px; width: 100px; height: 200px; background-color: white; background-repeat: no-repeat; z-index: 10;"> </div> </div> <script language="javascript"> var s = setinterval(movei, 1000); function movei() { var c = document.getelementbyid("t"); var pc = c.getcontext("2d"); c.height = c.height; //秒 pc.linewidth = 3; pc.strokestyle = 'rgba(255,0,0,0.8)'; var now = new date(); var sindex = getxy(150, now.getseconds()); pc.moveto(400, 400); pc.lineto(sindex.x, sindex.y); pc.stroke(); pc.beginpath(); //分 pc.linewidth = 7; pc.strokestyle = 'rgba(50,50,50,0.8)'; var mindex = getxy(120, now.getminutes() + (now.getseconds() / 60)); pc.moveto(400, 400); pc.lineto(mindex.x, mindex.y); pc.stroke(); pc.beginpath(); //时 pc.linewidth = 10; pc.strokestyle = 'rgba(0,0,0,0.8)'; var hindex = getxy(80, ((now.gethours() > 12 ? now.gethours() - 12 : now.gethours()) + (now.getminutes() / 60)) * 5); pc.moveto(400, 400); pc.lineto(hindex.x, hindex.y); pc.stroke(); }; function getxy(r, t) { //计算分区 0,1,2,3 var a = parseint(t / 15); //分区角度 t = t - 15 * a; var y; var x; //基于分区的坐标计算 switch (a) { case 0: y = r - (r * math.cos(2 * math.pi / 360 * 90 * (t / 15))); x = r + (r * math.sin(2 * math.pi / 360 * 90 * (t / 15))); break; case 1: y = r + (r * math.sin(2 * math.pi / 360 * 90 * (t / 15))); x = r + (r * math.cos(2 * math.pi / 360 * 90 * (t / 15))); break; case 2: y = r + (r * math.cos(2 * math.pi / 360 * 90 * (t / 15))); x = r - (r * math.sin(2 * math.pi / 360 * 90 * (t / 15))); break; case 3: y = r - (r * math.sin(2 * math.pi / 360 * 90 * (t / 15))); x = r - (r * math.cos(2 * math.pi / 360 * 90 * (t / 15))); break; default: break; } y = (400 - r) + y; x = (400 - r) + x; return { 'x': x, 'y': y }; }; </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。