Learn creative coding writing simple programs

85. Using a background image, mousePressed and mouseReleased()

While programming you have to pay a lot of attention to details. For example, there is a function called mousePressed() and there is a variable called mousePressed. The function gets called once when we click with the mouse. The variable has a value of true or false depending on if the mouse is currently clicked or not.
Since I want to make a circle grow while the mouse is clicked, I should keep checking the mousePressed variable inside the draw() function. Each time I notice the mouse is pressed, I make the circle a little bit bigger.
But I need a way to make it smaller again, otherwise it would grow out of the screen at some point. I use a function called mouseReleased() to achieve this. That function is executed when I stop pressing the mouse button, so it's a great place to reset the size of my circle.
After trying these mouse related functions and variables we use for the first time an image as a parameter for the background() function. In all previous episodes we used a color instead, so we were erasing the whole screen with a color, often white or black. But as we can see now, it's possible to erase the screen using a photo.
We end the episode with a question that will be answered in the next episode: how to draw a new circle each time we click the mouse? The difficulty here is that I want to move a circle when I move the mouse, and make a circle stay there in the background when I click. If I wasn't moving a circle it would be easy. I could just remove the background() call, and then just draw a new circle each time I click. But if I want to move a circle, I need to call background() to keep erasing the circle I'm moving, otherwise it gets full of circles as I move the mouse. Tricky :)

Tags: mousePressed, mouseReleased, image, background

Code editor

You can make changes to the code below. Then

Questions and comments

Try to stay close to the topic of this episode. Use the Processing forums for help with unrelated Processing projects (or hire me for help ;-)

To indicate that a word in your comment is code, use the `backtick`. Example
Do `float` and `int` smell similar?
To highlight code blocks, surround it with ``` code-fences ``` like this:
``` void setup() { size(600, 600); } ```