or, start from the existing triangle example
and do it the hard way:
( just think that that rect() consists of 4 triangles you have to use the same code for )
// https://forum.processing.org/one/topic/how-to-fill-a-triangle-with-diagonal-lines.html
// https://discourse.processing.org/t/hatching-a-rect-with-diagonal-lines/7068
/*
float x1,y1, x2,y2, x3,y3, nbLines;
void setup(){
size(800, 600, P2D);
smooth();
randomize();
}
void draw(){
background(255);
triangle(x1,y1, x2,y2, x3,y3);
for(int i=0; i<nbLines; i++){
float xa = map(i,0,nbLines, x1, x3);
float ya = map(i,0,nbLines, y1, y3);
float xb = map(i,0,nbLines, x2, x3);
float yb = map(i,0,nbLines, y2, y3);
line(xa,ya, xb,yb);
}
noLoop();
}
void mousePressed(){
randomize();
loop();
}
void randomize(){
x1= random(width);
y1=random(height);
x2= random(width);
y2=random(height);
x3= random(width);
y3=random(height);
nbLines = random(15);
}
*/
float rx, ry, rw, rh; // main rect
float x1, y1, x2, y2, x3, y3, x4, y4, xa, ya, xb, yb, nbLines; // triangles and diagonal lines
void randomize() {
rw= random(width);
rh= random(height);
rx= random(width-rw);
ry= random(height-rh);
nbLines = random(5, 10);
x1 = rx;
y1 = ry;
x2 = rx+rw;
y2 = ry+rh;
x3 = rx+rw;
y3 = ry;
x4 = rx;
y4 = ry+rh;
}
void setup() {
size(500, 400);
randomize();
}
void draw() {
background(255);
draw_rect();
}
void draw_rect() {
stroke(0, 0, 200);
fill(200, 200, 0);
rect(rx, ry, rw, rh);
stroke(0, 200, 0);
for (int i=0; i<nbLines; i++) {
xa = map(i, 0, nbLines, x1, x3);
ya = map(i, 0, nbLines, y1, y3);
xb = map(i, 0, nbLines, x2, x3);
yb = map(i, 0, nbLines, y2, y3);
line(xa, ya, xb, yb);
}
for (int i=0; i<nbLines; i++) {
xa = map(i, 0, nbLines, x1, x4);
ya = map(i, 0, nbLines, y1, y4);
xb = map(i, 0, nbLines, x2, x4);
yb = map(i, 0, nbLines, y2, y4);
line(xa, ya, xb, yb);
}
stroke(0, 200, 200);
for (int i=0; i<nbLines; i++) {
xa = map(i, 0, nbLines, x3, x2);
ya = map(i, 0, nbLines, y3, y2);
xb = map(i, 0, nbLines, x4, x2);
yb = map(i, 0, nbLines, y4, y2);
line(xa, ya, xb, yb);
}
for (int i=0; i<nbLines; i++) {
xa = map(i, 0, nbLines, x3, x1);
ya = map(i, 0, nbLines, y3, y1);
xb = map(i, 0, nbLines, x4, x1);
yb = map(i, 0, nbLines, y4, y1);
line(xa, ya, xb, yb);
}
}
void mousePressed() {
randomize();
}