requestAnimationFrame()動畫例項程式碼

admin發表於2017-04-15

分享一段程式碼例項,它利用requestAnimationFrame()結合canvas實現了動畫效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
canvas {
  display: block;
  margin: 0 auto;
}
#box {
  margin-top: 100px;
  margin-bottom: 20px;
  text-align: center;
}
</style>
<script type="text/javascript">
function animaFuns() {
  var requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame || setAnimationFuns;
  })();
 
  function setAnimationFuns(callback) {
    window.setTimeout(callback, 5);
  }
  var canvas = null,
    context = null,
    i = 0,
    R = 180,
    int = null;
 
  function init() {
    canvas = document.createElement("canvas");
    canvas.width = 456;
    canvas.height = 456;
    context = canvas.getContext("2d");
    document.body.appendChild(canvas);
  }
 
  function draw() {
    i += 0.02;
    if (i < 2) {
      var PI = Math.PI * i;
    } else if (i >= 2) {
      i = 0;
    }
    var x = Math.sin(PI) * R + 225;
    var y = Math.cos(PI) * R + 225;
    context.fillStyle = '#eee';
    context.fillRect(0, 0, 456, 456);
    context.fillStyle = 'rgb(255,0,0)';
    context.beginPath();
    context.arc(x, y, 20, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
  }
  function animate() {
    draw();
    init = requestAnimFrame(animate);
  }
  var stopDom = document.getElementById("stopAnimation");
  var startDom = document.getElementById("startAnimation");
  stopDom.onclick = function() {
    cancelAnimationFrame(init);
  }
  startDom.onclick = function() {
    cancelAnimationFrame(init);
    init = requestAnimationFrame(animate);
  }
  init();
  animate();
}
window.onload = function() {
  animaFuns();
}
</script>
</head>
<body>
<div id="box">
  <button type="button" id="startAnimation">開始動畫</button>
  <button type="button" id="stopAnimation">停止動畫</button>
</div>
</body>
</html>

相關文章