canvas環形百分比進度條效果

螞蟻小編發表於2017-03-25

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

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
window.onload = function() {
  window.onload = function() {
 
  var canvas = document.getElementById("canvas");
  context = canvas.getContext('2d'); 
  centerX = canvas.width / 2;
  centerY = canvas.height / 2;
  rad = Math.PI * 2 / 100;
  speed = 0.1;
 
  function blueCircle(n) {
    context.save();
    context.strokeStyle = "#49f"; 
    context.lineWidth = 5;
    context.beginPath();
    context.arc(centerX, centerY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
    context.stroke();
    context.closePath(); 
    context.restore();
 
  }
 
  function whiteCircle() {
    context.save();
    context.strokeStyle = "white";
    context.beginPath();
    context.arc(centerX, centerY, 100, 0, Math.PI * 2, false);
    context.stroke(); 
    context.closePath(); 
    context.restore();
  }
 
  function text(n) {
    context.save();
    context.strokeStyle = "#49f";
    context.font = "40px Arial";
    context.strokeText(n.toFixed(0) + "%", centerX - 25, centerY + 10);
    context.stroke();
    context.restore();
  }
 
  (function drawFrame() {
    window.requestAnimationFrame(drawFrame, canvas);
    context.clearRect(0, 0, canvas.width, canvas.height);
 
    whiteCircle();
    text(speed);
    blueCircle(speed);
 
    if (speed > 100) speed = 0;
    speed += 0.1;
  }());
 
}
  var canvas = document.getElementById("canvas");
  context = canvas.getContext('2d');
  centerX = canvas.width / 2;
  centerY = canvas.height / 2;
  rad = Math.PI * 2 / 100;
  speed = 0.1;
 
  function blueCircle(n) {
    context.save();
    context.strokeStyle = "#49f";
    context.lineWidth = 5;
    context.beginPath();
    context.arc(centerX, centerY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
    context.stroke();
    context.closePath();
    context.restore();
 
  }
 
  function whiteCircle() {
    context.save();
    context.strokeStyle = "white";
    context.beginPath();
    context.arc(centerX, centerY, 100, 0, Math.PI * 2, false);
    context.stroke();
    context.closePath();
    context.restore();
  }
 
  function text(n) {
    context.save();
    context.strokeStyle = "#49f";
    context.font = "40px Arial";
    context.strokeText(n.toFixed(0) + "%", centerX - 25, centerY + 10);
    context.stroke();
    context.restore();
  }
 
  (function drawFrame() {
    window.requestAnimationFrame(drawFrame, canvas);
    context.clearRect(0, 0, canvas.width, canvas.height);
 
    whiteCircle();
    text(speed);
    blueCircle(speed);
 
    if (speed > 100) speed = 0;
    speed += 0.1;
  }());
 
}                
</script>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background:#000"></canvas>
</body>
</html>

相關文章