为每个像素 p5js 存储项目颜色值

Store Item color value for every pixel p5js

我制作了一个网格,我可以在其中使用获取和存储函数绘制每个像素 现在我还想在每次从颜色选择器更改颜色时存储颜色值。现在,当我选择一种颜色而不是停留在例如颜色时,网格上的所有单元格都会受到影响。当我选择红色时红色,当我选择绿色时保持红色。

代码如下:

let sizewidth = 17
let sizeheight = 17
function setup() {
  createCanvas(sizewidth*30, sizeheight*30);
    col = createColorPicker('#000000');
}

function draw() {
  background(255);
  for(y = 0; y < sizeheight; y++){
    for(x = 0; x < sizewidth; x++){
      if(getItem(x + ":" + y) == null){
          storeItem(x + ":" + y, false)
        }
      if(getItem(x + ":" + y) == true){
          fill(col.color());
      }
      rect(x*30, y*30, 30, 30)
      noFill()
    }
  }
}

function mouseClicked(){
  for(y = 0; y < sizeheight; y++){
    for(x = 0; x < sizewidth; x++){
      if(mouseX < x*30+30 && mouseX > x*30 && mouseY < y*30+30 && mouseY > y*30){
          storeItem(x + ":" + y, true)
      }
    }
  }
}

function keyTyped(){
  if(key == "c"){
    clearStorage()
  }
  }

我认为您可以存储颜色数据而不是布尔值,如下所示:

let sizewidth = 17
let sizeheight = 17
function setup() {
clearStorage()                                   // clearing the previous boolean data (can be deleted later)
  createCanvas(sizewidth*30, sizeheight*30);
    col = createColorPicker('#000000');
}

function draw() {
  background(255);
  for(y = 0; y < sizeheight; y++){
    for(x = 0; x < sizewidth; x++){
      if(getItem(x + ":" + y) == null){
          storeItem(x + ":" + y, [255,255,255])        // filling all white
        }
      else {
                let c = getItem(x + ":" + y);          // getting color
                fill(c[0],c[1],c[2]);                  // fill cell with the color
      }
      rect(x*30, y*30, 30, 30)
      noFill()
    }
  }
}

function mouseClicked(){
  for(y = 0; y < sizeheight; y++){
    for(x = 0; x < sizewidth; x++){
      if(mouseX < x*30+30 && mouseX > x*30 && mouseY < y*30+30 && mouseY > y*30){
                let c = col.color();
                storeItem(x + ":" + y, [red(c),green(c),blue(c)]);    // storing the color
      }
    }
  }
}

function keyTyped(){
  if(key == "c"){
    clearStorage()
  }
  }