width 和 height 在调用 size() 之前没有实际值。仅仅因为您将变量放在函数之后,并不意味着它们在setup() 运行之后被分配:所有全局变量都被分配在任何函数运行之前。所以在这种情况下,你最终的宽度和高度都为 0,这将绝对不会绘制任何内容,因为没有要着色的像素 =)
你想要这个:
// let's put our global vars up top, to prevent confusion.
// Any global variable that isn't just declared but also
// initialised, gets initialised before *anything* else happens.
int rows, cols;
int[][] myArray;
// Step 2 is that setup() runs
void setup(){
size(800,800);
// now we can initialise values:
rows = width;
cols = height;
myArray = new int[rows][cols];
}
// Setup auto-calls draw() once, and
// then draw() runs at a specific framerate
// unless you've issued noLoop() at some point.
void draw(){
background(255);
for (int i=0;i<cols;i=i+10){
for (int j=0;j<rows;j=j+10){
myArray[i][j]=int(random(255));
}
}
for (int i=0;i<cols;i=i+10){
for (int j=0;j<rows;j=j+10){
fill(myArray[i][j]);
rect(i,j,i+10,j+10);
}
}
}
也就是说,这里我们甚至不需要rows 和cols,我们可以直接使用width 和height,我们不需要两个循环,我们只需要一个,因为我们'绘制矩形时不要使用尚未设置的相邻像素。我们只需要一直跳过 10,您已经这样做了:
int[][] myArray;
// Step 2 is that setup() runs
void setup() {
size(800,800);
myArray = new int[width][height];
}
void draw() {
background(255);
int i, j, step = 10;
for (i=0; i<height; i=i+step) {
for (j=0; j<width; j=j+step) {
myArray[i][j]=int(random(255));
fill(myArray[i][j]);
rect(i,j,i+step,j+step);
}
}
}