Melandin
Melandin

Reputation: 15

Store Item color value for every pixel p5js

I made a grid where i can draw every pixel using the get and store function and now I want to store also the color value every time I change the color from the color picker. Right now all the cells on the grid are affected when I choose a color instead of staying in e.g. red when I choose red and stay red when I choose green.

Below is the code:

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

Upvotes: 0

Views: 106

Answers (1)

hayabuzo
hayabuzo

Reputation: 98

I think that you can store the color data instead of boolean value, like this:

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

Upvotes: 1

Related Questions