欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

canvas绘制表盘时钟

程序员文章站 2023-10-31 17:32:28
话不多说,请看代码:

话不多说,请看代码:

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>canvas绘制表盘</title>
</head>
<body>
 <canvas id='box' width="500" height="500" >
 您的浏览器不支持canvas
 </canvas>
 <script>
 var box = document.getelementbyid('box');
 var cxt = box.getcontext('2d');
 // 时钟动起来
 var timer = null;
 function clock(){
 var date = new date();
 var h = date.gethours();
 h = h + h/60;
 h = h>12? h-12:h;
 var m = date.getminutes();
 var s = date.getseconds();
 // 清画布
 cxt.clearrect(0,0,500,500); 
 // 画表盘
 cxt.strokestyle = '#f0f';
 cxt.linewidth = 6;
 cxt.beginpath();
 cxt.arc(250,250,100,0,2*math.pi);
 cxt.stroke();
 // 画时钟刻度
 for(var i=0; i<12; i++){
 cxt.save();
 cxt.translate(250,250);
 cxt.rotate(30*i*math.pi/180);
 cxt.linewidth = 3;
 cxt.beginpath();
 cxt.moveto(0,-80);
 cxt.lineto(0,-92);
 cxt.stroke();
 cxt.restore();
 }
 //画分钟刻度
 for(var i=0; i<60; i++){
 cxt.save();
 cxt.translate(250,250);
 cxt.rotate(6*i*math.pi/180);
 cxt.linewidth = 2;
 cxt.beginpath();
 cxt.moveto(0,-86);
 cxt.lineto(0,-92);
 cxt.stroke();
 cxt.restore();
 }
 // 画时针
 cxt.save();
 cxt.linewidth = 5;
 cxt.translate(250,250);
 cxt.rotate(h*30*math.pi/180);
 cxt.beginpath();
 cxt.moveto(0,6);
 cxt.lineto(0,-40);
 cxt.stroke();
 cxt.restore();
 // 画分针
 cxt.save();
 cxt.linewidth = 3;
 cxt.translate(250,250);
 cxt.rotate(m*6*math.pi/180);
 cxt.beginpath();
 cxt.moveto(0,8);
 cxt.lineto(0,-60);
 cxt.stroke();
 cxt.restore();
 // 画秒针
 cxt.save();
 cxt.linewidth = 1;
 cxt.translate(250,250);
 cxt.rotate(s*6*math.pi/180);
 cxt.beginpath();
 cxt.moveto(0,10);
 cxt.lineto(0,-75);
 cxt.stroke();
 cxt.restore();
 // 画中心的小圆固定三根针
 cxt.save();
 cxt.beginpath();
 cxt.fillstyle = '#0f0';
 cxt.linewidth = 2;
 cxt.translate(250,250);
 cxt.arc(0,0,2,0,360,false);
 cxt.stroke();
 cxt.fill();
 cxt.restore();
 // 画秒针上的园
 cxt.save();
 cxt.fillstyle = '#f00';
 cxt.linewidth = 2;
 cxt.translate(250,250);
 cxt.rotate(s*6*math.pi/180);
 cxt.beginpath();
 cxt.arc(0,-60,2,0,360,false);
 cxt.stroke();
 cxt.fill();
 cxt.restore();
 }
 clock();
 timer = setinterval(clock,1000);
 </script>
</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!