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()
  }
 

表盤數(shù)字

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);//定時器

看完了要贊一下哦~ 轉載請注明出處 感謝感謝~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容