Canvas 绘制小手表.

作者: 刘英俊_02 | 来源:发表于2016-05-19 22:17 被阅读0次
小手表.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);//定时器

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

相关文章

网友评论

    本文标题:Canvas 绘制小手表.

    本文链接:https://www.haomeiwen.com/subject/oaegrttx.html