canvas實現判斷兩球是否碰撞效果

admin發表於2017-02-17

本章節分享一段程式碼例項,它實現了判斷兩球是否碰撞的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var c1 = {
  x: 100,
  y: 100,
  r: 50,
  color: 'palegreen'
}
var c2 = {
  x: 200,
  y: 200,
  r: 70,
  color: 'deeppink'
}
var cs = [c1, c2];
var index = -1;
  
function drawRect() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < cs.length; i++) {
    ctx.beginPath();
    ctx.fillStyle = cs[i].color;
    ctx.arc(cs[i].x, cs[i].y, cs[i].r, 0, Math.PI * 2, false);
    ctx.fill();
    if (arguments.length) {
      if (ctx.isPointInPath(arguments[0], arguments[1])) {
        index = i;
      }
    }
  }
}
drawRect();
canvas.onmousedown = function(e) {
  var ev = e || window.event;
  // 滑鼠座標
  var x = ev.clientX;
  var y = ev.clientY;
  drawRect(x, y);
  if (index == -1) {
    return;
  }
  var oldX = x - cs[index].x;
  var oldY = y - cs[index].y;
  canvas.onmousemove = function(e) {
    var ev = e || window.event;
    cs[index].x = ev.clientX - oldX;
    cs[index].y = ev.clientY - oldY;
    drawRect();
    pengZhuang(c1, c2);
  }
  canvas.onmouseup = function() {
    index = -1;
    canvas.onmousemove = null;
  }
}
  
function pengZhuang(obj1, obj2) {
  var dis = obj1.r + obj2.r;
  var DISX = (obj1.x - obj2.x) * (obj1.x - obj2.x);
  var DISY = (obj1.y - obj2.y) * (obj1.y - obj2.y);
  if (dis >= Math.sqrt(DISX + DISY)) {
    alert("撞上了");
  }
}
</script>
</body>
</html>

相關文章