This week we looked at making a painting program.
We started with three built in P5.js variables:
- mouseIsPressed – true whenever the mouse button is held down
- mouseX – contains the X position of the mouse pointer
- mouseY – contains the Y position of the mouse pointer
We put the call to background() in the setup() function because we didn’t want to clear the background every frame. After that, in the draw() function, we just needed to draw an circle at the mouse’s position every time the mouse button was pressed.
This gave us an very basic painting program in just a few lines of code!
We then looked at the idea of a toolbar to contain buttons for selecting colours and the size of the brush.
We first need to decide where it would be (the left side of the screen) and we created a variable toolbarSize to store the width of it.
In the draw() function we then added a check not to draw an circle if we were inside the toolbar area.
We then added a new function called mouseClicked(). This is a special function name (like setup() and draw()) that P5.js will call at the appropriate time. In this case its called when the mouse is clicked (button pressed down and the released).
Colour and Sizes
We created two arrays to store a list of colours and brush sizes at the top of our script:
let colours = ['black', 'white', 'red', 'blue', 'green'];
let sizes = [5, 10, 20, 40, 80, 160];
To draw the toolbar, we made a new function called drawToolbar() and put a call to it in our draw() function. In the new function, we looped over the colours array, drawing a new button, filled with the respective colour and then another loop over sizes drawing a square with a circle inside to represent the brush size. We needed to scale those circles to make them fit inside our buttons.
Detecting Selected Button
Since everything in our toolbar was toolbarSize high, to determine what had been clicked on, we just needed to divide mouseY by toolbarSize to get the index of the button that had been clicked on. We looked at that index, if it was less than the number of colours, we must have clicked on a colour. If greater, it had to be a size (or beyond the end).
Selected colours and selected sizes were stored in two variables called currentColour and currentSize respectively and used within the draw() function when creating our circles.
Mark suggested that people draw a portrait of me to test our new program and there were some brilliant renderedings. Three people were kind enough to share theirs with me so that I could put them here. I think they’re great!
The files for this week can be found on our GitHub repository.