Problem with keyPressed when drawing a square

hiii,i am trying to add a square to the canvas when a key is pressed and i want it to remain on the canvas when the key is released . but it disappears when is released the key .can anybody
help me??
here is my code

int squareSize=6;
final float DIFF_SIZE=1;
final int MIN_COLOUR=1;
final int MAX_COLOUR=10;
final float INIT_RED=100,INIT_GREEN=50,INIT_BLUE=80;
final float FINAL_RED=255,FINAL_GREEN=200,FINAL_BLUE=250;
final float MAX_SIZE=40;
final float X_SPACING =10;
final float Y_SPACING=10;
 float squareX,squareY;
void setup(){
size(600,600);}


void draw()
{
 squareX=mouseX-squareSize/2;
squareY=mouseY-squareSize/2;
  background(255);

 drawRowsOfBlocks();

 }


    
  void drawOneBlock()
  {
    
   
    rect(squareX,squareY,squareSize,squareSize);
    for(int i=MIN_COLOUR; mousePressed && i <=MAX_COLOUR/10; i++)
  { float redValue=INIT_RED+(i-MIN_COLOUR)/(MAX_COLOUR-MIN_COLOUR)*(FINAL_RED-INIT_RED);
    float greenValue=INIT_GREEN+(i-MIN_COLOUR)/(MAX_COLOUR-MIN_COLOUR)*(FINAL_GREEN-INIT_GREEN);
    float blueValue=INIT_BLUE+(i-MIN_COLOUR)/(MAX_COLOUR-MIN_COLOUR)*(FINAL_BLUE-INIT_BLUE);  
    fill(redValue,greenValue,blueValue);
    rect(squareX,squareY,squareSize,squareSize);
    squareSize+=DIFF_SIZE;
  }
  if (squareSize>MAX_SIZE)
  {
    squareSize=6;}
  }
  
  void drawRowsOfBlocks()
  { drawOneBlock();
  
for (int i=1;keyPressed&& i<=2;i++)
    { drawOneBlock();
    
 float squareY2;
 squareY2=squareY+squareSize+Y_SPACING;
squareY=squareY2;
 }}
1 Like

Hey Karan,

There’s a mouseClicked() function which is called after the mouse has been pressed and released, perhaps this would better serve you here?

Also, please remember to format your code correctly by clicking the </> button in the editor, or wrapping the code in back ticks (`). This makes it much easier to read!

1 Like