-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfractal.js
112 lines (93 loc) · 2.33 KB
/
fractal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var c = document.getElementById("fracCanvas");
var ctx = c.getContext("2d");
c.width = window.innerWidth;
c.height = window.innerHeight;
ctx.fillStyle="#EEEEEE";
var margTop = 120;
var margLeft = 120;
var numFractals = 2;
var fractal = Math.floor(Math.random() * numFractals); //0: cantor; 1: dragon curve
//cantor set
var cantorHeight = 40;
var cantorWidth = window.innerWidth - margLeft * 2;
var cantorVGap = 30;
var cantorHGap = 10;
var cantorPos = margTop;
//dragon curve
var dc_iter = 10;
var dragon_curve = [0,0,1];
var dragon_curve_tmp = dragon_curve;
if(fractal==1) {
for(var j=0; j < dc_iter; j++) {
dragon_curve_tmp = dragon_curve.slice();
dragon_curve_tmp.push(0);
for(var k=0; k < dragon_curve.length; k++) {
if(dragon_curve[k]==0) {
dragon_curve[k] = 1;
}
else {
dragon_curve[k] = 0;
}
}
for(var k=0; k < dragon_curve.length; k++) {
dragon_curve_tmp.push(dragon_curve[dragon_curve.length-1-k]);
}
dragon_curve = dragon_curve_tmp.slice();
}
//alert(dragon_curve);
var scale = 20;
var lp_x = 0;
var lp_y = 1;
var x = window.innerWidth/4;
var y = window.innerHeight/2;
ctx.beginPath();
ctx.moveTo(x,y);
x += lp_x * scale;
y += lp_y * scale;
ctx.lineTo(x,y);
ctx.stroke();
}
var i = 0;
window.setInterval(function(){drawFrac();}, (fractal==1)?100:1000);
function drawFrac() {
if(fractal==1) {
if(i>=dragon_curve.length) return;
var nlp_x = 0;
var nlp_y = 0;
if(dragon_curve[i]==0) {//right
nlp_x = 0* lp_x + 1* lp_y;
nlp_y = -1* lp_x + 0* lp_y;
}
else {//left
nlp_x = 0* lp_x + -1* lp_y;
nlp_y = 1* lp_x + 0* lp_y;
}
lp_x = nlp_x;
lp_y = nlp_y;
ctx.beginPath();
ctx.moveTo(x,y);
x += lp_x * scale;
y += lp_y * scale;
ctx.lineTo(x,y);
ctx.stroke();
}
else {
if(i>6) return;
if(i==0) {
ctx.fillRect(margLeft,cantorPos,cantorWidth,cantorHeight);
}
else {
var numEle = Math.pow(2,i);
var numGaps = numEle - 1;
var curWidth = (cantorWidth - numGaps * 2 * cantorHGap) / numEle;
for(var j=0; j < numGaps; j++) {
ctx.fillRect(margLeft,cantorPos,curWidth,cantorHeight);
ctx.fillRect(margLeft+(curWidth+2*cantorHGap)*(j+1),cantorPos,curWidth,cantorHeight);
}
}
cantorPos += cantorHeight + cantorVGap;
cantorHeight--; if(cantorHeight<1) cantorHeight = 1;
cantorVGap--; if(cantorVGap<1) cantorVGap = 1;
}
i++;
}