canvas擺動效果程式碼例項

螞蟻小編發表於2017-02-26
分享一段程式碼例項,它實現了擺動效果,類似於老式機械鐘錶鐘擺的效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
body {
  margin: 0;
  padding: 0;
}
#canvas {
  border: 2px solid gray;
  box-shadow: 10px 10px 10px 10px cyan;
  margin: auto;
  display: block;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var r = 250;
var colorList = "abcdefABCDEF0123456789".split("");
var colorListLength = colorList.length;
var color = function() {
  var _color = "#";
  for (var i = 0; i < 6; i++) {
    _color += colorList[Math.round(Math.random() * colorListLength)];
  }
  return _color;
};
var createArc = function(attrs) {
  ctx.save();
  ctx.beginPath();
  ctx.fillStyle = color();
  ctx.arc(attrs.x, attrs.y, attrs.r, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
};
var createLine = function(from, to) {
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(from.x, from.y);
  ctx.lineTo(to.x, to.y);
  ctx.stroke();
  ctx.closePath();
  ctx.restore();
}
var createAll = function() {
  createArc({
    x: 300,
    y: 20,
    r: 10
  });
  createArc({
    x: Math.cos(angle) * r + 300,
    y: Math.sin(angle) * r + 200,
    r: 20
  });
  createLine({
    x: 300,
    y: 20
  }, {
    x: Math.cos(angle) * r + 300,
    y: Math.sin(angle) * r + 200
  });
};
var minAngle = 0;
var maxAngle = Math.PI;
var addAngle = Math.PI / 30;
var angle = minAngle;
var mode = "left";
var interval = setInterval(function() {
  // var y = Math.sin(angle)*r+200;
  // var x = Math.cos(angle)*r+250;
  switch (mode) {
    case "left":
      ctx.clearRect(0, 0, 600, 500);
      createAll();
      angle += addAngle;
      if (angle > maxAngle) {
        mode = "right";
        angle -= addAngle;
        return;
      }
      break;
    case "right":
      ctx.clearRect(0, 0, 600, 500);
      createAll();
      angle -= addAngle;
      if (angle < minAngle) {
        mode = "left";
        angle += addAngle;
        return;
      }
      break;
  }
}, 50);
</script>
</body>
</html>

相關文章