Adding objects to the canvas fom within the mousePressed() method

draw is you friend ! even if you do nothing, you need it.

right now you “setup” your display and make it black. after that nothing can happen, because draw does not run. even when you leave it empty and use the rest of your code “as is”, you will see it works.
“real” programmers will probably stone me for saying this, but it does not matter (most of the time) where your code is written to. at least for your purpose, to get more intimate with processing :wink:

saying:

void setup() {
  size(400, 400);
}
void draw() {
  background(0, 0, 0);
  ellipse(mouseX, mouseY, 10, 10);
}
void drawAnEllipse () {
}

is the same as:

void setup() {
  size(400, 400);
}
void draw() {
  background(0, 0, 0);  
  drawAnEllipse();
}
void drawAnEllipse() {
  ellipse(mouseX, mouseY, 10, 10);
}

think of the method as a roadsign where your code makes a little detour :wink:

it is not inappropriate to use draw ! one of the good reasons to use a method is to keep your code understandable for… yourself. if you have really a lot of lines, it makes sense to break your code down into different parts and put them into methods which you then call from inside draw.

it is not so dissimilar to why people invented for-loops (somewhere back in the stoneage I think…).

instead of writing “ellipse (x,y,10,10);” 100 times, writing down different x,y values for different positions,
it is (in part) better to write:

for (int i=0;i<100;i++) {
ellipse (x,y,10,10);
}

now you could even do uncanny stuff like having a formula for x, every round… or x and y.

for (int i=0;i<100;i++) {
ellipse (x,y,10,10);
x = random (0,100);
y = random (0,100);
}

mousePressed () is “special” because, similar to draw(), it runs all the time. (like mouseReleased() and others. mouseX and mouseY are also update every frame when your code runs.

yet draw() is the thing that… well, draws to the display, makes sure that the code is executed repeatedly.

4 Likes