DIV CSS 佈局教程網

用 Canvas 畫互不重疊的圓:隨機生成與碰撞偵測
編輯:關於JavaScript     

這個練習同時動用到 Canvas 繪圖與一個經典的計算幾何判斷:兩圓是否相交。核心洞察是——不用真的算距離再開根號,直接比較「距離平方」與「半徑和的平方」即可,省掉一次 Math.sqrt。

執行結果:

HTML

<canvas id="my_canvas" width="500" height="400">
  your browser does not support canvas
</canvas>
<button id="my_btn">Another Circle</button>

JavaScript

var context = document.getElementById("my_canvas");
context = context.getContext("2d");

var circles = [];
var width = 500;
var height = 400;
var max_radius = 30;
var min_radius = 20;
var count = 0;

window.onload = function () {
  var btn = document.getElementById("my_btn");
  btn.onclick = function () {
    make_circle();
  };
};

function Circle(x, y, r, color) {
  this.x = x;
  this.y = y;
  this.r = r;
  this.color = color;
}

function make_circle() {
  var x = Math.floor(Math.random() * width) + 1;
  var y = Math.floor(Math.random() * height) + 1;
  var r = Math.floor(Math.random() * (max_radius - min_radius)) + min_radius;
  // 隨機產生不同的顏色
  var color = "rgb(" + (Math.floor(Math.random() * 256)) + ","
            + (Math.floor(Math.random() * 256)) + ","
            + (Math.floor(Math.random() * 256)) + ")";

  var circle = new Circle(x, y, r, color);

  if (test1(circle) && test2(circle)) {
    circles.push(circle);
    context.strokeStyle = color;
    context.beginPath();
    context.arc(x, y, r, 0, Math.PI * 2, true);
    context.closePath();
    context.stroke();
    count = 0;
  } else {
    count++;
    // 連續失敗太多次,代表已經沒有空間可放
    if (count > 10000) {
      alert("no more circle");
      return false;
    }
    make_circle();
  }
}

// 檢查新圓是否與既有圓相交
function test1(circle) {
  var len = circles.length;
  for (var i = 0; i < len; i++) {
    var x1 = circles[i].x, y1 = circles[i].y, r1 = circles[i].r;
    var x2 = circle.x, y2 = circle.y, r2 = circle.r;
    // 比較距離平方與半徑和的平方,避免開根號
    if ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) < (r2 + r1) * (r2 + r1)) {
      return false;
    }
  }
  return true;
}

// 檢查新圓是否超出畫布邊界
function test2(circle) {
  if ((circle.x + circle.r) > width || (circle.y + circle.r) > height ||
      (circle.x - circle.r) < 0 || (circle.y - circle.r) < 0) {
    return false;
  }
  return true;
}

兩個可以改進的地方

遞迴深度。make_circle 在失敗時直接呼叫自己,畫布接近填滿時可能連續遞迴上萬層,有堆疊溢出的風險。改成 while 迴圈搭配失敗計數會更穩健。

碰撞偵測的效能。test1 每次都掃過全部既有圓,是 O(n²) 的做法。圓數量上千時,可以改用空間分割(網格或四叉樹)只檢查鄰近的格子,大幅降低比較次數。另外半徑目前只取 20–30,若允許更小的半徑,能塞進去的數量會明顯增加。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved