Hong-Phuc Bui
2025-01-16 2889de7f0c2d587a17fbd322af57c29e84238620
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
/**
 * barnsley-fern.js
 * Plot a Barnsley fern to the JXG Board
 */
import "./lib/dfhi.js";
import * as JXG from "jsxgraph" ;
import {exportBoard} from "./lib/dfhi-plot";
 
/**
 * the JXG Board
 * */
let board = undefined;
/**
 * called only once, as page loaded, as required by "lib/dfhi.js" API
 * */
window.init = function() {
    board = initBoard();
    function exportSvg(event) {
        exportBoard(board);
    }
    document.getElementById("export")
        .addEventListener("click", exportSvg);
};
 
/**
 * called every time user clicks on the #run Button, as required by "lib/dfhi.js"
 * */
window.main = function(...argv) {
    if (board) {
        try {
            JXG.JSXGraph.freeBoard(board);
            board = undefined;// remove all child of boad
            board = initBoard();
        }catch (e) {
            console.log(e);
            console.log(board);
        }
    }
    let n = Number.parseInt(argv[0]);
    let points = barnsley(n);
    let opt = {withLabel:false, fixed:true, size:0.001, fillColor:"#00aa00", strokeWidth:0};
    plotBarnsley(board, points, opt);
};
 
/**
 * init board, called at least once by window.init
 * */
function initBoard() {
    return JXG.JSXGraph.initBoard('plotter', {
        boundingbox: [-6, 12, 6, -1],
        axis: false,
        keepAspectRatio:true
    });
}
 
 
/**
 * generates points of Barnsley Fern.
 * */
function barnsley(n) {
    const m = [
        [ 0    ,  0    , 0     , 0.16 , 0.500   , 0    , 0.01],
        [ 0.85 ,  0.04 , -0.04 , 0.85 , 0.075   , 1.60 , 0.85],
        [ 0.20 , -0.26 , 0.23  , 0.22 , 0.400   , 1.60 , 0.07],
        [-0.15 ,  0.28 , 0.26  , 0.24 , 0.575   , 0.44 , 0.07]
    ];
    const p = [ m[0][6], m[0][6] + m[1][6], m[0][6] + m[1][6] + m[2][6] ];
    let x = 0, y = 0;
    const points = [ [x, y] ];
    for(let i = 0; i < n; ++i) {
        let r = Math.random();
        let f = 0;
        if (r < p[0]) {
            f = 0;
        }else if (r < p[1]) {
            f = 1;
        }else if (r < p[2]) {
            f = 2;
        } else {
            f = 3;
        }
        let nX = (m[f][0] * x) + (m[f][1] * y) + m[f][4];
        y =  (m[f][2] * x) + (m[f][3] * y) + m[f][5];
        x = nX;
        points.push([x,y]);
    }
    return points;
}
 
/**
 *
 * @param board
 * @param points
 * @param attr
 *
 * */
function  plotBarnsley(board, points, attr ) {
    for(let p of points) {
        board.create('point', p, attr );
    }
}