canvas實現的小球四壁碰撞效果程式碼例項

admin發表於2017-02-10
本章節分享一段程式碼例項,它利用canvas實現了小球在一個封閉區域四壁碰撞效果。

程式碼比較簡單,裡面涉及到了不少關於canvas的小知識點,感興趣的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
div {
  width: 610px;
  height: 610px;
  margin: 0px auto;
}
</style>
</head>
<body>
<div>
  <canvas id="canvas" width="600" height="600" style="border:1px solid #ccc;"></canvas>
</div>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "#0ff";
var ban = {
  X: 20,
  Y: 20,
  H: 1,//水平方向
  V: 1,//垂直方向
  h: null,//水平的方向增量
  v: null,//垂直的方向增量
  timer: null,
  init: function () {
    var me = this;
    me.h = me.rFn();
    me.v = me.rFn();
    me.timer = setInterval(me.move.bind(this), 5);
  },
  newRect: function (x, y) {//重新整理頁面
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillRect(x, y, 50, 50);
  },
  move: function () {//移動方塊
    //如果碰到左邊
    if (this.X == 0) {
      this.H = -this.H;
      this.h = this.rFn();
    }
    //如果碰到右邊
    if ((this.X + 50) == canvas.width) {
      this.H = -this.H;
      this.h = this.rFn();
    }
    //如果碰到上邊
    if (this.Y == 0) {
      this.V = -this.V;
      this.v = this.rFn();
    }
    //如果碰到下邊
    if ((this.Y + 50) == canvas.width) {
      (this.V = -this.V);
      this.v = this.rFn();
    }
 
    this.X += (this.H * this.h);
    this.Y += (this.V * this.v);
 
    (this.X + 50) >= canvas.width && (this.X = canvas.width - 50);
    this.X <= 0 && (this.X = 0);
    (this.Y + 50) >= canvas.height && (this.Y = canvas.height - 50);
    this.Y <= 0 && (this.Y = 0);
    this.newRect(this.X, this.Y);
  },
  rFn: function () {//隨機生成數字
    return Math.floor(Math.random() * 10) + 1;
  },
}
window.onload = function () {
  ban.init();
}
</script>
</body>
</html>

相關文章