用javascript畫圓

 Tue, 04 Sep 2007 17:59:45 +0800

恩,純動腦筋,好玩用的。之前做過產生直線與多邊形的方法,但是畫圓用的方法比較不同,所以試一下。

function circle (x,y,r) {
var points = [];
for (var i = 0; i> (-Math.round(r/Math.sqrt(2))-1); i--) {
j = Math.sqrt(Math.pow(r,2) - Math.pow(i,2));
if (Math.ceil(j)-j > j-Math.floor(j)) {
j = Math.floor(j);
} else {
j = Math.ceil(j);
}
points.push({"x":i+x,"y":j+y});
points.push({"x":i+x,"y":y-j});
points.push({"x":x-i,"y":j+y});
points.push({"x":x-i,"y":y-j});
points.push({"x":j+x,"y":i+y});
points.push({"x":j+x,"y":y-i});
points.push({"x":x-j,"y":i+y});
points.push({"x":x-j,"y":y-i});
}
return points;
}

上面這個函數會根據座標與半徑,傳回圓周的點集合。再用下面這個函數來畫:

function plot (x, y, target) {
var div=document.createElement("div");
div.style.position = "absolute";
div.style.height = "1px";
div.style.width = "1px";
div.style.left = x + "px";
div.style.top = y + "px";
div.style.fontSize = "1px";
div.innerHTML = " ";
div.style.padding = "0px";
div.style.margin = "0px";
div.style.background = "black";
div.style.clip = "rect(0,1,1,0)";
target.appendChild(div);
}

最後測試一下:

var a = circle(120, 120, 100);
alert(a.length);
for (var m=0; m<a.length; m++) {
plot(a[m].x,a[m].y,document.body);
}

這樣就會畫出一個以座標(120,120)為圓心,半徑為100的圓。像下面這張圖:

test107

繪圖原理?簡單地說,圓周上每一個點(x,y)會符合x^2+y^2=r^2的條件。過來的問題是如何組合。我是從最下面一點開始,每次x值減一來求出y值,因為斜率剛好,所以線會連在一起,弧線的長度不超過圓周的八分之一(因為超過的話,線就不會連在一起),最後再往八個方向做mirror,這樣就構成整個圓了。(不過因為計算的關係,也許陣列裡面會有少許重複的點)