Skip to content

Instantly share code, notes, and snippets.

@donno2048
Created January 16, 2022 22:14
Show Gist options
  • Save donno2048/fc1306b0d4cddd58c84530ddaa140e1f to your computer and use it in GitHub Desktop.
Save donno2048/fc1306b0d4cddd58c84530ddaa140e1f to your computer and use it in GitHub Desktop.
// cute demo for line drawing in p5js
async function setup() {
createCanvas(400, 400);
background(0);
stroke(0, 200, 0);
fill(0, 200, 0);
const distance = 25;
for (var i = 0; i < 300 / distance + 1; i++) {
drawLine(new p5.Vector(50 + distance * i, 350), new p5.Vector(50 + distance * i, 50), 50, 1);
await drawLine(new p5.Vector(50, 350 - distance * i), new p5.Vector(350, 350 - distance * i), 50, 1);
}
await sleep(500);
beginShape();
vertex(50, 50);
vertex(50, 350);
vertex(350, 350);
vertex(350, 50);
endShape(CLOSE);
await sleep(1000);
removeElements();
background(0);
drawLine(new p5.Vector(50, 50), new p5.Vector(50, 350), 1, 0);
drawLine(new p5.Vector(50, 50), new p5.Vector(350, 50), 1, 0);
drawLine(new p5.Vector(350, 350), new p5.Vector(50, 350), 1, 0);
drawLine(new p5.Vector(350, 350), new p5.Vector(350, 50), 1, 0);
var edges;
for (i = 0; i < 30; i++) {
edges = [1, 2, 3, 4];
const edge1 = random(edges);
edges = edges.filter((edge) => edge != edge1);
const edge2 = random(edges);
const point1 = rPoint(edge1);
const point2 = rPoint(edge2);
stroke(200, 0, 0);
await drawLine(point1, point2, 50, 10);
stroke(0, 200, 0);
await drawLine(point1, point2, 1, 0);
}
}
async function drawLine(a, b, chunks, delay) {
const width = b.x - a.x;
const height = b.y - a.y;
for (var i = 0; i < chunks; i++) {
line(a.x + width * (i / chunks), a.y + height * (i / chunks), a.x + width * ((i + 1) / chunks), a.y + height * ((i + 1) / chunks));
await sleep(delay);
}
}
function rPoint(edge) {
switch (edge) {
case 1:
return new p5.Vector(50, random(75, 325));
case 2:
return new p5.Vector(350, random(75, 325));
case 3:
return new p5.Vector(random(75, 325), 50);
case 4:
return new p5.Vector(random(75, 325), 350);
}
}
function sleep(t) {return new Promise((_) => {setTimeout(_, t);})}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment