canvas百分比環形進度條程式碼

antzone發表於2018-07-17

分享一段程式碼例項,它利用canvas實現了百分比進度條效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.progress {
  width: 200px;
  height: 200px;
  border: solid 1px #ccc;
  position: absolute;
  transform: rotate(-90deg);
}
#canvas1, #canvas2 {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
}
#canvas2 {
  transform: rotate(90deg);
}
</style>
<script>
window.onload = function() {
  function $id(id) {
    return typeof id === "string" ? document.getElementById(id) : id;
  }
 
  function progress(maxAngle) {
    var canvas1 = $id("canvas1");
    var conText1 = canvas1.getContext("2d"); //2d物件
    conText1.lineWidth = 10; //線條寬度
    conText1.beginPath();
    conText1.strokeStyle = "#ccc"; //筆觸顏色
    conText1.arc(100, 100, 95, 0, 2 * Math.PI, false); //繪製圓形
    conText1.stroke(); //連結起兩點
    conText1.closePath(); //連結起始點和終結點
 
    //轉動的圓環
    //轉動的最大度數maxAngle
    var canvas2 = $id("canvas2");
    var conText2 = canvas1.getContext("2d"); //2d物件
    conText2.lineWidth = 10;
    var grd = conText2.createLinearGradient(100, 10, 0, 100); //建立一個線性漸變
    grd.addColorStop(1, "#8CE050");
    grd.addColorStop(0, "#f00");
    //設定fillStyle為當前的漸變物件
    conText2.strokeStyle = grd;
    var angle = 0; //角度
    var timer = null; //定時器
    timer = setInterval(function() {
      if (angle < maxAngle / 100 * 360) {
        angle++;
      } else {
        clearInterval(timer);
      }
      var progress = parseInt((angle / 360) * 100); //%顯示
      conText2.beginPath();
      conText2.arc(100, 100, 95, 0, angle * Math.PI / 180, false);
      conText2.clearRect(0, 0, 200, 200); //走完一次清空一次
      conText2.stroke();
      conText2.closePath();
      conText2.rotate(90 * Math.PI / 180) //旋轉的弧度
      conText2.font = "30px Arial"; //字型屬性
      conText2.fillStyle = "#000000"
      var text = progress + "%";
      conText2.fillText(text, 80, -90);
      conText2.closePath();
      conText2.restore(); //返回之前儲存過的路徑狀態和屬性
    }, 10)
  }
  progress(50);
}
</script>
</head>
<body>
  <div class="progress">
    <canvas id="canvas1" height="200" width="200"></canvas>
    <canvas id="canvas2" height="200" width="200"></canvas>
  </div>
</body>
</html>

相關文章