樹木曲線


樹木曲線的1次、2次與3次繪圖如下所示:


其中每一次遞迴所使用的leng、angle與branch三個參數如1次樹木曲線所示,這三個參數適當的調整,就可以繪製出不同形狀的樹木結構,而不一 定要遵守一定的比例或規則。

下面是樹木曲線的Java演算程式:
  • TreeCurve.java
package cc.openhome;

import java.awt.*;
import javax.swing.JApplet;

public class TreeCurve extends JApplet {
private static final double INIT_LENG = 100.0; // 分枝長度
private static final double INIT_ANGLE = 90.0; // 分枝與地面的夾角
private static final double INIT_BRANCH = 20.0; // 分枝的分岐角

private Turtle t = new Turtle();
 
public void init() {
setSize(350, 400);
setBackground(Color.black);
}

public void tree(int n, double x0, double y0,
double leng, double angle, double branch,
double scale1, double scale2) {
if (n == 0) {
return;
}

t.setPoint(x0, y0);
t.setAngle(angle);
t.move(leng);
// Turtle 目前的位置
double x = t.getCurrentX();
double y = t.getCurrentY();

tree(n - 1, x, y, leng * scale1,
angle + branch, branch, scale1, scale2);
tree(n - 1, x, y, leng * scale2,
angle - branch, branch, scale1, scale2);
}

public void paint(Graphics g) {
g.setColor(Color.yellow);

t.setGraphics(g);
t.window(0, 0, getWidth(), getHeight());
t.view(0, 0, getWidth(), getHeight());

tree(8, 180, 0, INIT_LENG, INIT_ANGLE, INIT_BRANCH, 0.7, 0.7);
}
}

以下是上面的Applet看到的畫面:


如果將遞迴時的參數改為以下(您可以試試不同的參數),可以繪製出不同的樹木結構:
tree(8, 230, 0, leng, angle, branch, 0.8, 0.6);

以下是使用HTML5 Canvas的方式(如果瀏覽器支援HTML5 Canvas,例如最新版的Firexfox、Chrome、IE9等,可以直接將下面的內容存為HTML或按下檔名連結,直接載入瀏覽器執行觀看結果:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=Big5" http-equiv="content-type">
<script type="text/javascript" src="js/turtle.js"></script>
<script type="text/javascript">
window.onload = function() {
function tree(n, x0, y0, leng, angle, branch,
scale1, scale2) {
if (n == 0) {
return;
}

turtle.setPoint(x0, y0);
turtle.setAngle(angle);
turtle.move(leng);
// Turtle 目前的位置
var x = turtle.currentX;
var y = turtle.currentY;

tree(n - 1, x, y, leng * scale1,
angle + branch, branch, scale1, scale2);
tree(n - 1, x, y, leng * scale2,
angle - branch, branch, scale1, scale2);
}

var INIT_LENG = 100;
var INIT_ANGLE = 90;
var INIT_BRANCH = 20;

var canvas1 = document.getElementById('canvas1');
var context = canvas1.getContext('2d');
var turtle = new Turtle(context);

turtle.window(0, 0, canvas1.width, canvas1.height);

turtle.view(0, 0, canvas1.width, canvas1.height);

tree(8, 230, 0,
INIT_LENG, INIT_ANGLE, INIT_BRANCH, 0.8, 0.6);
};
</script>
</head>
<body>
<canvas id="canvas1" width="350" height="400"></canvas>
</body>
</html>

以下是在Firefox中看到的畫面: