canvas圓環百分比載入效果程式碼例項

admin發表於2017-02-23
分享一段程式碼例項,它實現了圓環百分比載入效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
canvas {
  border: 3px solid transparent;
  margin: 0 auto;
  display: block;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var canvas = document.getElementById("myCanvas");
  var canvasObj = canvas.getContext("2d");
  var deg = 90;
 
  function draw() {
    canvasObj.clearRect(0, 0, canvas.width, canvas.height);
    deg++;
 
    canvasObj.beginPath();
    canvasObj.arc(300, 300, 200, 0, Math.PI * 2, false);
 
    canvasObj.fillStyle = "#ddd";
    canvasObj.fill();
 
    canvasObj.beginPath();
    canvasObj.arc(300, 300, 150, 0, Math.PI * 2, false);
    canvasObj.shadowBlur = 10;
    canvasObj.shadowColor = "black";
 
    canvasObj.fillStyle = "#eee";
    canvasObj.fill();
 
    canvasObj.beginPath();
    canvasObj.arc(300, 300, 160, -Math.PI / 180 * 90, (-Math.PI / 180 * deg), true);
    canvasObj.lineWidth = 20;
 
    var linearG = canvasObj.createLinearGradient(300, 120, 300, 470);
 
    linearG.addColorStop(0, "deepskyblue");
    linearG.addColorStop(1, "purple");
 
    canvasObj.strokeStyle = linearG;
    canvasObj.stroke();
 
    canvasObj.textAlign = "center";
    canvasObj.fillStyle = "greenyellow";
    canvasObj.font = "80px serif";
    var str = Math.floor((deg - 90) / 360 * 100) + "%";
    canvasObj.fillText(str, 300, 320);
    if (deg == 450) {
      clearInterval(timer);
    }
  }
  var timer = setInterval(draw, 20);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="600"></canvas>
</body>
</html>

相關文章