Canvas 绘制小手表.

小手表.gif

话不多说啦,给大家分享我写的小手表源码~

<style type="text/css"> 
body{ background-color: black; text-align: center; }

Canvas的套路是 每次都清空画布 再重新画上所有(我是这么理解的~)

<body> <canvas id="myCanvas" width="800" height="800" style="border: 1px solid black;"></canvas> </body>

JS部分 先获取

var canvas=document.getElementById('myCanvas'); 
var ctx=canvas.getContext('2d'); 
var deg=Math.PI/180;

定义全局

quanju()
function quanju(){ ctx.clearRect(0,0,canvas.width,canvas.height);

获取当前时间

var now=new Date(); 
var h=now.getHours(); 
var m=now.getMinutes(); 
var s=now.getSeconds(); 
var ms=now.getMilliseconds();

表盘外圈

var now=new Date(); 
var h=now.getHours(); 
var m=now.getMinutes(); 
var s=now.getSeconds(); 
var ms=now.getMilliseconds();

表盘内刻度

for(var i=0;i<12;i++){
    ctx.beginPath();
    ctx.moveTo(400+(Math.sin(i*30*deg)*200),400-(Math.cos(i*30*deg)*200));
    ctx.lineTo(400+(Math.sin(i*30*deg)*(200+20)),400-(Math.cos(i*30*deg)*(200+20)));
    ctx.stroke()
  }
 

表盘数字

for(var i=0;i<12;i++){
  var txts=[12,1,2,3,4,5,6,7,8,9,10,11];
  ctx.beginPath();
  ctx.font='25px KaiTi';
  ctx.fillStyle='white'
  ctx.fillText(txts[i],392+(Math.sin(i*30*deg)*180),410-(Math.cos(i*30*deg)*180))
  }

阴影~

ctx.shadowBlur=15;
  ctx.shadowColor='pink'
  ctx.shadowOffsetX=1;
  ctx.shadowOffsetY=1;

时针

var hx=400+100*(Math.sin(h*30*deg+m*0.5*deg));
  var hy=400-100*(Math.cos(h*30*deg+m*0.5*deg));
  ctx.beginPath();
  ctx.moveTo(400,400);
  ctx.lineTo(hx,hy);
  ctx.strokeStyle='red';
  ctx.lineCap='round';
  ctx.lineWidth=10;
  ctx.stroke();

分针 如果想让秒针转一圈分针跳动一下到下一格就去掉+s0.1deg哦~

var mx=400+130*(Math.sin(m*6*deg+s*0.1*deg));
  var my=400-130*(Math.cos(m*6*deg+s*0.1*deg));
  ctx.beginPath();
  ctx.moveTo(400,400);
  ctx.lineTo(mx,my);
  ctx.strokeStyle='cornflowerblue';
  ctx.lineWidth=6;
  ctx.stroke();

秒针同理

var sx=400+160*(Math.sin(s*6*deg+ms*0.006*deg));
  var sy=400-160*(Math.cos(s*6*deg+ms*0.006*deg));
  ctx.beginPath();
  ctx.moveTo(400,400);
  ctx.lineTo(sx,sy);
  ctx.strokeStyle='ghostwhite';
  ctx.lineWidth=2;
  ctx.stroke();

随便加上一行文字~哈哈

var txt='Patek Philippe';
  ctx.beginPath();
  ctx.font='15px black'
  ctx.fillStyle='white'
  ctx.fillText(txt,350,300)
  }

加全局定时器

  timer=setInterval(function(){
   quanju()
  },50);//定时器

看完了要赞一下哦~ 转载请注明出处 感谢感谢~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容