requestAnimationFrame()动画实例代码

快乐打工仔 分类:实例代码

分享一段代码实例,它利用requestAnimationFrame()结合canvas实现了动画效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

requestAnimationFrame()动画实例代码,这样的场景在实际项目中还是用的比较多的,关于requestAnimationFrame()动画实例代码就介绍到这了。

requestAnimationFrame()动画实例代码属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容