当前位置:Gxlcms > JavaScript > JS+H5 Canvas实现时钟效果

JS+H5 Canvas实现时钟效果

时间:2021-07-01 10:21:17 帮助过:2人阅读

用JavaScript+Canvas来实现最简单的时钟效果,供大家参考,具体内容如下

效果图:

先看html代码:

  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <title></title>
  5. <script type="text/javascript" src="js/demo3.js" ></script>
  6. </head>
  7. <body>
  8. <canvas id = "canvas"></canvas>
  9. </body>
  10. </html>

JavaScript代码:

  1. var canvas,context;
  2. function draw(){//定义划时钟的方法
  3. var data = new Date();
  4. var hHoure = data.getHours();
  5. var mMin = data.getMinutes();
  6. var sSec = data.getSeconds();
  7. var hValue = (hHoure*30+mMin/2-90)*Math.PI/180;
  8. var mValue = (mMin*6-90)*Math.PI/180;
  9. var sValue = (sSec*6 -90)*Math.PI/180;
  10. var x = 200,y = 200,r = 150;
  11. context.clearRect(0,0,canvas.width,canvas.height);
  12. context.moveTo(x,y);
  13. context.arc(x,y,r,0,6*Math.PI/180,false);
  14. //
  15. context.beginPath();
  16. context.lineWidth = 1;
  17. for(var i = 0;i<60;i++){
  18. context.moveTo(x,y);
  19. context.arc(x,y,r,6*i*Math.PI/180,6*(i+1)*Math.PI/180,false);
  20. }
  21. context.closePath();
  22. context.stroke();
  23. //
  24. context.beginPath();
  25. context.fillStyle = "white";
  26. context.moveTo(x,y);
  27. context.arc(x,y,r/1.1,-0,2*Math.PI,false);
  28. context.closePath();
  29. context.fill();
  30. //
  31. context.beginPath();
  32. context.lineWidth = 3;
  33. for(var i = 0;i<12;i++){
  34. context.moveTo(x,y);
  35. context.arc(x,y,r,30*i*Math.PI/180,30*(i+1)*Math.PI,false);
  36. }
  37. context.closePath();
  38. context.stroke();
  39. //
  40. context.beginPath();
  41. context.fillStyle = "white";
  42. context.moveTo(x,y);
  43. context.arc(x,y,r/1.12,0,2*Math.PI,false);
  44. context.closePath();
  45. context.fill();
  46. context.beginPath();
  47. context.fillStyle = "black";
  48. context.moveTo(x,y);
  49. context.arc(x,y,r/30,0,2*Math.PI,false);
  50. context.fill();
  51. //
  52. context.beginPath();
  53. context.lineWidth = 5;
  54. context.moveTo(x,y);
  55. context.arc(x,y,r/2.5,hValue,hValue,false);
  56. context.stroke();
  57. //
  58. context.beginPath();
  59. context.lineWidth = 3;
  60. context.moveTo(x,y);
  61. context.arc(x,y,r/2,mValue,mValue,false);
  62. context.stroke();
  63. //
  64. context.beginPath();
  65. context.lineWidth = 2;
  66. context.moveTo(x,y);
  67. context.arc(x,y,r/1.6,sValue,sValue,false);
  68. context.stroke();
  69. }
  70. window.onload = function(){
  71. canvas = document.getElementById('canvas');
  72. context = canvas.getContext('2d');
  73. canvas.height = 500;
  74. canvas.width = 500;
  75. setInterval(draw,1000);
  76. draw();
  77. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行