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

js Canvas绘制圆形时钟效果

程序员文章站 2023-12-06 11:42:52
本文实例为大家分享了js canvas圆形时钟的具体实现代码,供大家参考,具体内容如下 ...

本文实例为大家分享了js canvas圆形时钟的具体实现代码,供大家参考,具体内容如下

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>canvas clock</title>
    <style type="text/css">

      div{
        text-align: center;
        margin-top: 250px;
      }
      #clock{

        border: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <div>
      <canvas id="clock" height="200px" width="200px"></canvas>
    </div>

    <script type="text/javascript" src="js/clock.js"></script>
  </body>
</html>

js

var dom=document.getelementbyid('clock');
var cxt=dom.getcontext("2d");
var width=cxt.canvas.width;
var height=cxt.canvas.height;
var r=width/2;

function drawbackground(){
  cxt.save();
  cxt.translate(r,r);
  cxt.beginpath();
  cxt.linewidth=10;
  cxt.arc(0,0,r-5,0,2*math.pi,false);
  cxt.stroke();
  cxt.font="18px arial";
  cxt.textalign='center'
  cxt.textbaseline='middle'
  var hournums=[3,4,5,6,7,8,9,10,11,12,1,2];
  hournums.foreach(function(number,i){

    var rad=2*math.pi/12*i;
    var x=math.cos(rad)*(r-30);
    var y=math.sin(rad)*(r-30);
    cxt.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);
    var y=math.sin(rad)*(r-18);
    cxt.beginpath();
    if(i % 5===0){
      cxt.fillstyle="#000"
      cxt.arc(x,y,2,0,2*math.pi,false);
    }
    else{
      cxt.fillstyle="#ccc"
      cxt.arc(x,y,2,0,2*math.pi,false);
    }
    cxt.fill(); 
  }

}

function drawhour(hour,minute){
  cxt.save();
  cxt.beginpath();
  var rad=2*math.pi/12*hour;
  var mrad=2*math.pi/12/60*minute
  cxt.rotate(rad+mrad);
  cxt.linewidth=6;
  cxt.linecap='round'
  cxt.moveto(0,10);
  cxt.lineto(0,-r/2);
  cxt.stroke();
  cxt.restore();
}

function drawminute(minute){
  cxt.save();
  cxt.beginpath();
  var rad=2*math.pi/60*minute;
  cxt.rotate(rad);
  cxt.linewidth=3;
  cxt.linecap='round'
  cxt.moveto(0,10);
  cxt.lineto(0,-r+30);
  cxt.stroke();
  cxt.restore();
}

function drawsecond(second){
  cxt.save();
  cxt.beginpath();
  cxt.fillstyle='#c14543'
  var rad=2*math.pi/60*second;
  cxt.rotate(rad);  
  cxt.moveto(-2,20);
  cxt.lineto(2,20);
  cxt.lineto(1,-r+18);
  cxt.lineto(-1,-r+18);
  cxt.fill();
  cxt.restore();
}

function drawdot(){

  cxt.beginpath();
  cxt.fillstyle='#fff'
  cxt.arc(0,0,3,0,2*math.pi,false);
  cxt.fill();
}

function draw(){

  cxt.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();
  cxt.restore();
}
draw();
setinterval(draw,1000);

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