Welcome, guest | Sign In | My Account | Store | Cart

Sierpinski Triangle Fractal using Line Automaton (1D CA). The 1D CA rule used is actually Pascal's Triangle Mod 2. Tested only using Firefox 3.5.

JavaScript, 73 lines
 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
<html>
<head><title>Sierpinski Triangle Fractal using HTML5 Canvas</title></head>
<body>

<canvas id="canvas" width="514" height="514">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

<script type="text/javascript">
// Sierpinski Triangle Fractal using Line Automaton (1D CA).
// The 1D CA rule used is actually Pascal's Triangle Mod 2.
// FB - 201007051
// Tested only using Firefox 3.5

// globals
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var xr = context.canvas.width;
var yr = context.canvas.height;
var imgd = context.createImageData(xr,yr);
var pix = imgd.data;
var rd = 0;
var gr = 0;
var bl = 0;
var al = 0;

function putpixel(ix, iy, rd, gr, bl, al)
{
    var p = (yr * iy + ix) * 4;
    pix[p]   = rd % 256; // red
    pix[p+1] = gr % 256; // green
    pix[p+2] = bl % 256; // blue
    pix[p+3] = al % 256; // alpha
}

function getpixel(ix, iy)
{
    var p = (yr * iy + ix) * 4;
    rd = pix[p];   // red
    gr = pix[p+1]; // green
    bl = pix[p+2]; // blue
    al = pix[p+3]; // alpha
}

// seed
var rd0 = Math.floor(Math.random() * 128) + 1;
var gr0 = Math.floor(Math.random() * 128) + 1;
var bl0 = Math.floor(Math.random() * 128) + 1;
putpixel(xr - 1, 0, rd0, gr0, bl0, 255);

var rd1 = 0;
var gr1 = 0;
var bl1 = 0;

for(var ky = 1; ky < yr - 1; ky++)
{
    for(var kx = 0; kx < xr - 1; kx++)
    {
        getpixel(kx, ky - 1);
        rd1 = rd;
        gr1 = gr;
        bl1 = bl;
        getpixel(kx + 1, ky - 1);
        if((rd1 == 0 && rd > 0) || (rd1 > 0 && rd == 0)) // XOR
            putpixel(kx, ky, rd0, bl0, gr0, 255);
    }
}

context.putImageData(imgd, 0,0);

</script>
</body>
</html>

1 comment

rolftenkate 12 years, 6 months ago  # | flag

Thank you, FB36, for pointing me to the existence of the canvas-tag and showing me how to use it in JS. I'm a JS newbie looking for things to experiment on, and this will definitely be one of my focuses. I've done cellular automata in about every language i learned since 1981, and thx to U i'm sure CA and JS will be a great and sweet adventure. I'll vote you UP for this.

Created by FB36 on Wed, 7 Jul 2010 (MIT)
JavaScript recipes (69)
FB36's recipes (148)

Required Modules

  • (none specified)

Other Information and Tasks