canvas加载效果代码实例

2018-7-9 14:52| 作者: admin| 查看: 340| 评论: 0|来自: 蚂蚁部落

本章节分享一段代码实例,它利用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>

鲜花

握手

雷人

路过

鸡蛋

最新评论

返回顶部