Colour Change Of Ellipse

I’ve been trying to make a code where if I press a specific box it will change the colour of the pen (that I’m using ellipse to make). I was able to make it change to red when I press a certain box but I can’t make it do another colour. This is the code I have so far:

void draw(){
if(mousePressed==true){
ellipse(mouseX,mouseY,20,20);
if(mousePressed==true&&mouseX<50){
if(mousePressed==true&&mouseY<50){
fill(255,0,0);
}
}
}
}

Hey!

Welcome to the forum!

Great to have you here!

What I did:

  • You need to check x and y position of the mouse. You can combine this with && which means AND. You check if mouseX and mouseY is within a rect.

  • In the example below I assume the buttons are rectangles and are under each other on the left side. So their x-position is the same, but the y-position is different.

  • Explanation: So mouseX must be bigger than left side of the rectangle and smaller than right side. And mouseY bigger than upper side and smaller than lower side. (In this case we don’t check whether mouseX is > 0 because the buttons are on the left side anyway)

  • Also, you can use a function mousePressed() to keep your code tidy. It gets called automatically. It’s used for the color buttons but not for the drawing. The function mousePressed() registers a mouse click only once, the variable mousePressed in the function draw() registers throughout, so you can draw continuously.

  • Use noStroke() to get rid of the outline of the ellipse.

Remark

It might be necessary to store the chosen color in a color variable. That would make it possible to draw the color of the buttons in red and blue and still have the ellipse color red (from the color variable). Otherwise the colors would interfere.

Warm regards,

Chrisir


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

void draw() {
  if (mousePressed && mouseX > 50) {
    ellipse(mouseX, mouseY, 20, 20);
  }
}

void mousePressed() {
  if (mouseX<50 && 
    mouseY>0 &&  
    mouseY<55 ) {
    fill(0, 255, 0);
  } else if (mouseX<50 && 
    mouseY>55 &&  
    mouseY<119) {
    fill(255, 0, 0);
  }
}//

3 Likes