Skip to content

Instantly share code, notes, and snippets.

@alvinometric
Created May 5, 2023 22:28
Show Gist options
  • Save alvinometric/d8d46db1eaffed884f128ff72994fb5f to your computer and use it in GitHub Desktop.
Save alvinometric/d8d46db1eaffed884f128ff72994fb5f to your computer and use it in GitHub Desktop.
Barnsley Fern in JavaScript (and Canvas)
// paste this in a codepen, JSBin, etc
// https://rosettacode.org/wiki/Barnsley_fern#JavaScript
var d = document;
var cv = d.createElement("canvas");
d.body.appendChild(cv);
var c = cv.getContext("2d");
var cw = 300;
var ch = 300;
cv.width = cw;
cv.height = ch;
var x = 0,
y = 0,
xw = 0,
yw = 0,
r;
function rand(m) {
return Math.floor(Math.random() * m);
}
c.fillStyle = "#fff";
c.fillRect(0, 0, cw, ch);
for (var i = 0; i < 10000; i++) {
r = rand(100);
if (r <= 1) {
xw = 0;
yw = 0.16 * y;
} else if (r <= 8) {
xw = 0.2 * x - 0.26 * y;
yw = 0.23 * x + 0.22 * y + 1.6;
} else if (r <= 15) {
xw = -0.15 * x + 0.28 * y;
yw = 0.26 * x + 0.24 * y + 0.44;
} else {
xw = 0.85 * x + 0.04 * y;
yw = -0.04 * x + 0.85 * y + 1.6;
}
x = xw;
y = yw;
c.fillStyle = "#0a0";
c.fillRect(x * cw * 0.05 + cw / 2, -y * ch * 0.06 + ch * 0.9, 1, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment