以正方為基礎的十字繡,其1次與2次曲線如下所示:
以下為四個十字繡曲線所圍成的小方巾圖案程式:
- StachCurve.java
package cc.openhome;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class StechCurve extends JApplet {
private Turtle t = new Turtle();
public void init() {
setSize(350, 350);
setBackground(Color.black);
}
public void stech(int n, double leng) {
if(n == 0) {
t.move(leng);
}
else {
stech(n-1, leng); t.turn(-90);
stech(n-1, leng); t.turn(90);
stech(n-1, leng); t.turn(90);
stech(n-1, leng); t.turn(-90);
stech(n-1, leng);
}
}
public void paint(Graphics g) {
g.setColor(Color.yellow);
t.setGraphics(g);
t.window(0, 0, getWidth(), getHeight());
t.view(0, 0, getWidth(), getHeight());
t.setPoint(100, 100);
t.setAngle(0);
for(int i = 1; i <= 4; i++) {
stech(4, 2);
t.turn(90);
}
}
}
以下是使用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 stech(n, leng) {
if(n == 0) {
turtle.move(leng);
}
else {
stech(n-1, leng); turtle.turn(-90);
stech(n-1, leng); turtle.turn(90);
stech(n-1, leng); turtle.turn(90);
stech(n-1, leng); turtle.turn(-90);
stech(n-1, leng);
}
}
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);
turtle.setPoint(100, 100);
turtle.setAngle(0);
for(var i = 1; i <= 4; i++) {
stech(4, 2);
turtle.turn(90);
}
};
</script>
</head>
<body>
<canvas id="canvas1" width="350" height="350"></canvas>
</body>
</html>
以下是在Firefox中看到的結果: