【问题标题】:Processing: no output from code within draw()处理:draw() 中的代码没有输出
【发布时间】:2014-08-02 04:41:42
【问题描述】:

在下面的代码中,它运行没有错误,但没有输出。但是,当我从 draw() 循环中删除代码时,它会成功输出。 如果我将代码放在 for 循环中,那么输出只会出现在 for 循环的末尾,而不是在 for 循环期间。 我不明白为什么在这两种情况下都没有输出。

void setup(){
  size(800,800);
}

int rows = height;
int cols = width;
int [][] myArray = new int[rows][cols];

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);
    } 
  }
}

【问题讨论】:

    标签: processing


    【解决方案1】:

    widthheight 在调用 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);
        }  
      }
    }
    

    也就是说,这里我们甚至不需要rowscols,我们可以直接使用widthheight,我们不需要两个循环,我们只需要一个,因为我们'绘制矩形时不要使用尚未设置的相邻像素。我们只需要一直跳过 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);
        }  
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 2023-03-21
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多