您现在的位置是:网站首页> 编程资料编程资料

用HTML5的canvas实现一个炫酷时钟效果Html5 canvas实现粒子时钟的示例代码HTML写一个网页动态时钟HTML5实现可缩放时钟代码使用html5 canvas 画时钟代码实例分享用HTML5制作数字时钟的教程html5绘制时钟动画html5时钟实现代码HTML 罗盘式时钟的实现

2023-10-13 316人已围观

简介 下面小编就为大家带来一篇用HTML5的canvas实现一个炫酷时钟效果。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

对于H5来说,canvas可以说是它最有特色的一个地方了,有了它之后我们可以随意的在网页上画各种各样的图形,做一些小游戏啊什么的。canvas这个标签的用法,在网上也有特别多的教程了,这里就不作介绍了。今天我们就用canvas来做一个小小的时钟。

那么首先在这个页面里面我使用了两个canvas,一个用来绘制静态的时钟表盘和刻度,另一个用来绘制时钟的三个指针,然后用定位让他们重合到一起。然后这里没什么好说的,下面附上代码。

JavaScript Code复制内容到剪贴板
  1. "plate">   
  2.         画表盘   
  3.   
  4. "needles">   
  5.         画时针   
  6.   
JavaScript Code复制内容到剪贴板
  1. var plate=document.getElementById('plate');   
  2. var needles=document.getElementById('needles');   
  3. needles.setAttribute('style','position:absolute;top:8px;left:8px;');  //这里因为chrome里面,body的magin值为8px,所以我这里就没设为0了。   
  4. var cntP=plate.getContext('2d');   
  5. var cntH=needles.getContext('2d');   
  6. plate.width=800;   
  7. plate.height=500;   
  8. needles.width=800;   
  9. needles.height=500;  

到了这里准备工作就做完了,下面就准备绘制时钟了。我先定义了一个绘制时钟表盘的构造函数。

JavaScript Code复制内容到剪贴板
  1. function drawclock(cnt,radius,platelen,linewidth,numLen,NUMLEN){   
  2.             this.cnt=cnt;   
  3.             this.radius=radius;   
  4.             this.platelen=platelen;   
  5.             this.linewidth=linewidth;   
  6.             this.numLen=numLen;   
  7.             this.NUMLEN=NUMLEN;   
  8.             this.getCalibCoor=function(i){     
  9.                 //获得表盘刻度两端的坐标   
  10.                 var X=200+this.radius*Math.sin(6*i*Math.PI/180);   
  11.                 var Y=200-this.radius*Math.cos(6*i*Math.PI/180);   
  12.                 var x=200+(this.radius-this.platelen)*Math.sin(6*i*Math.PI/180);   
  13.                 var y=200-(this.radius-this.platelen)*Math.cos(6*i*Math.PI/180);   
  14.   
  15.                 // 获得分钟数字的坐标   
  16.                 var numx=200+(this.radius-this.platelen-this.numLen)*Math.sin(6*i*Math.PI/180);   
  17.                 var numy=200-(this.radius-this.platelen-this.numLen)*Math.cos(6*i*Math.PI/180);   
  18.                 //获得小时数字的坐标   
  19.                 var numX=200+(this.radius-this.platelen-this.NUMLEN)*Math.sin(6*i*Math.PI/180);     
  20.                 var numY=200-(this.radius-this.platelen-this.NUMLEN)*Math.cos(6*i*Math.PI/180);   
  21.                 return {X:X,Y:Y,x:x,y:y,numx:numx,numy:numy,numX:numX,numY:numY};   
  22.             };   
  23.             this.drawCalibration=function(){ //画刻度   
  24.                 for(var i=0,coorObj;i<60;i++){   
  25.                     coorObj=this.getCalibCoor(i);   
  26.                     this.cnt.beginPath();   
  27.                     this.cnt.moveTo(coorObj.X,coorObj.Y);   
  28.                     this.cnt.lineTo(coorObj.x,coorObj.y);   
  29.                     this.cnt.closePath();   
  30.   
  31.                     this.cnt.lineWidth=this.linewidth;   
  32.          

相关内容

-六神源码网