canvas繪製圓盤走動鐘錶效果

admin發表於2018-09-09

分享一段程式碼例項,利用canvas實現繪製鐘錶的功能,並且鐘錶指標能夠自動走動,實時的獲取本機時間。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  padding: 0;
  margin: 0;
}
body {
  background: #ccc;
}
#c {
  background: #fff;
}
</style>
<script>
window.onload = () => {
  let oC = document.getElementById('c');
  let oC1 = oC.getContext('2d');
  
  let toDraw = () => {
    let x = 200; // x軸座標
    let y = 200; // y軸座標
    let r = 150; // r 半徑
    // 清空畫布
    oC1.clearRect(0, 0, oC.width, oC.height)
      // 獲取時間
    let oDate = new Date();
    let oHours = oDate.getHours(); //時
    let oMin = oDate.getMinutes(); //分
    let oSen = oDate.getSeconds(); //秒
  
    let oHoursVal = (oHours * 30 - 90 + oMin / 2) * Math.PI / 180;
    let oMinVal = (oMin * 6 - 90) * Math.PI / 180;
    let oSenVal = (oSen * 6 - 90) * Math.PI / 180;
  
    // 繪製秒針錶盤
    oC1.beginPath();
    for (let i = 0; i < 60; i++) {
      oC1.moveTo(x, y);
      oC1.arc(x, y, r, 6 * i * Math.PI / 180, 6 * (i + 1) * Math.PI / 180, false);
    }
    oC1.closePath();
    oC1.stroke();
  
    // 繪製大圓盤 (覆蓋)
    oC1.fillStyle = "#fff";
    oC1.beginPath();
    oC1.moveTo(x, y);
    oC1.arc(x, y, r * 0.95, 0, 360 * Math.PI / 180, false);
    oC1.closePath();
    oC1.fill();
  
    // 繪製分針錶盤
    oC1.lineWidth = 3;
    oC1.beginPath();
    for (let i = 0; i < 12; i++) {
      oC1.moveTo(x, y);
      oC1.arc(x, y, r, 30 * i * Math.PI / 180, 30 * (i + 1) * Math.PI / 180, false);
    }
    oC1.closePath();
    oC1.stroke();
    // 繪製大圓盤 (覆蓋)
    oC1.fillStyle = "#fff";
    oC1.beginPath();
    oC1.moveTo(x, y);
    oC1.arc(x, y, r * 0.9, 0, 360 * Math.PI / 180, false);
    oC1.closePath();
    oC1.fill();
  
    // 繪製時針
    oC1.lineWidth = 5;
    oC1.beginPath();
    oC1.moveTo(x, y);
    oC1.arc(x, y, r * 0.5, oHoursVal, oHoursVal, false);
    oC1.closePath();
    oC1.stroke();
  
    // 繪製分針
    oC1.lineWidth = 3;
    oC1.beginPath();
    oC1.moveTo(x, y);
    oC1.arc(x, y, r * 0.7, oMinVal, oMinVal, false);
    oC1.closePath();
    oC1.stroke();
  
    // 繪製秒針
    oC1.lineWidth = 1;
    oC1.beginPath();
    oC1.moveTo(x, y);
    oC1.arc(x, y, r * 0.8, oSenVal, oSenVal, false);
    oC1.closePath();
    oC1.stroke();
  
    // 中心點
    // 繪製大圓盤 (覆蓋)
    oC1.fillStyle = "red";
    oC1.beginPath();
    oC1.moveTo(x, y);
    oC1.arc(x, y, r * 0.05, 0, 360 * Math.PI / 180, false);
    oC1.closePath();
    oC1.fill();
  }
  setInterval(toDraw, 1000)
  toDraw()
}
</script>
</head>
<body>
  <canvas id="c" height="400" width="400"></canvas>
</body>
</html>

相關文章