canvas載入效果程式碼例項

admin發表於2018-07-09
本章節分享一段程式碼例項,它利用canvas實現了載入效果。

不知道怎麼描述效果,直接看程式碼演示:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#canvas {
  box-shadow: 5px 5px 5px #ccc;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<button>開始動畫</button>
<script>
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;
var btn = document.getElementsByTagName("button")[0];
 
function loading() {
  var num = 0;
  var x = canvas.width / 2;
  var y = canvas.height / 2;
  var ctx = canvas.getContext("2d");
  var arc_increment = 0;
  ctx.lineWidth = 3;
  var timer;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
 
  function draw() {
    ctx.strokeStyle = '#176785';
    ctx.beginPath();
    ctx.arc(x, y, 100, (0.5 + arc_increment - 0.02) * Math.PI, (0.5 +
 
      arc_increment) * Math.PI);
    ctx.stroke();
    ctx.closePath();
 
    var color = ctx.createLinearGradient(x + 50, y + 100, x + 50, y - 100);
    color.addColorStop(0, "#499989");
    color.addColorStop(1, "#176785");
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, 100, (0.5 - arc_increment / 2) * Math.PI, (0.5 + arc_increment /
 
      2) * Math.PI);
    ctx.closePath();
    ctx.fill();
 
    ctx.font = "50px Arial";
    ctx.fillStyle = "#fff";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.beginPath();
    ctx.fillText(num, x, y);
    ctx.closePath();
    arc_increment += 0.02;
    num += 1;
    if (num > 100) {
      clearInterval(timer);
    }
  }
 
  timer = setInterval(draw, 100);
}
btn.addEventListener("click", loading);
</script>
</body>
</html>

相關文章