xxxxxxxxxx
57
const order = 3;
var N = 1 << order; // 2**order
var npts = N * N;
const path = [];
function setup() {
createCanvas(512, 512);
var L = width / N;
// console.log(pts[0]);
for (let i = 0; i < npts; i++) {
path[i] = hilbert(i);
path[i].mult(L);
path[i].add(L/2, L/2);
}
noLoop();
}
function draw() {
background(220);
stroke(20);
strokeWeight(3);
noFill();
beginShape();
for (let i = 0; i < npts; i++) {
vertex(path[i].x, path[i].y);
}
endShape();
}
function hilbert(p) {
const pts = [
new p5.Vector(0,0),
new p5.Vector(0,1),
new p5.Vector(1,1),
new p5.Vector(1,0)];
let index = p & 3;
let v = pts[index].copy();
let i = p >>> (2 * (order - 1));
if (i == 0) {
let tmp = v.x;
v.x = v.y;
v.y = tmp;
}
if (i == 3) {
let tmp = -1-v.x;
v.x = 1-v.y;
v.y = tmp;
}
v.add(pts[i].mult(2));
return v;
}