xxxxxxxxxx
158
const canvas_wh = 600;
async function setup() {
createCanvas(canvas_wh, canvas_wh);
background(0);
fill(51);
colorMode(RGB);
dir_forwards = true
do {
// make a random color r/g/b by making random int 0-255,
// then convert to hex, and zero pad
let r = Math.floor(Math.random() * 255).toString(16).padStart(2, '0');
let g = Math.floor(Math.random() * 255).toString(16).padStart(2, '0');
let b = Math.floor(Math.random() * 255).toString(16).padStart(2, '0');
console.log("next color:", `#${r}${g}${b}`);
await draw_hilbert(`#${r}${g}${b}`,`#${r}${g}${b}`, dir_forwards);
dir_forwards = !dir_forwards;
} while (true);
}
async function draw_hilbert(line_color, dot_color, dir_forwards) {
xy_max = 8 * 2;
line_len = xy_max * xy_max;
_scale = Math.floor(canvas_wh / xy_max - 2);
offset = 15 + (canvas_wh/2) - (xy_max * _scale) / 2;
draw_lines = true;
// rand
line_weight = Math.floor(Math.random() * (_scale - 1))
let start = 0;
let end = line_len;
let delta = 1;
let i = start;
if (!dir_forwards) {
start = end;
end = 1;
delta = -1;
i = start - 1;
}
let lx = 0;
let ly = 0;
do {
await asleep(1);
if (draw_lines && i > 0) {
[lx, ly] = d2xy(line_len, i - 1);
lx = offset + lx * _scale;
ly = offset + ly * _scale;
}
// this bit gets the xy, for i on the line len
[x, y] = d2xy(line_len, i);
// translate it a little
x = offset + x * _scale;
y = offset + y * _scale;
// set dot size / color
stroke(dot_color);
strokeWeight(line_weight);
await point(x, y);
if (draw_lines && i > 0) {
await line(lx, ly, x, y);
// await ease_line(lx, ly, x, y, line_color, line_weight, 0.5);
}
i += delta;
if (dir_forwards) {
if (i >= end) {
break
}
} else {
if (i <= end) {
break
}
}
// store last x / y
[lx, ly] = [x, y]
} while (true)
}
async function ease_line(start_x, start_y, end_x, end_y, _line_color, _line_weight, easing) {
let x = start_x;
let y = start_y;
console.log('........')
do {
stroke(_line_color);
strokeWeight(_line_weight);
x = x + Math.round((end_x - x) * easing);
y = y + Math.round((end_y - y) * easing);
console.log('easing from', [start_x, start_y], ' to ', [end_x, end_y], [x, y]);
// lol actually just redrawing the whole line...but
// whatver
await line(start_x, start_y, x, y);
await asleep(500);
} while (x < end_x && y < end_y) // this doesn't work as expected
}
function asleep(n) {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, n);
});
}
// get coords for n length curve at d distance
//
function d2xy(n, d) {
let rx = 0;
let ry = 0;
let t = d; // length of line desired
x = 0;
y = 0;
for (s = 1; s < n; s *= 2) {
rx = 1 & (t / 2);
ry = 1 & (t ^ rx);
[x, y] = rot(s, rx, ry);
x += s * rx;
y += s * ry;
t /= 4;
}
return [x, y];
}
function rot(n, rx, ry) {
if (ry == 0) {
if (rx == 1) {
x = n - 1 - x;
y = n - 1 - y;
}
//Swap x and y
t = x;
x = y;
y = t;
}
return [x, y];
}