How do I change an image (of fruit) each time the user clicks on it with their mouse? This is for a drawing app where the user selects ‘brushes’ to draw on the screen with their mouse.
/* global createCanvas, resizeCanvas */
let fruit = [];
let idx;
function preload () {
window.setupMenuLogic()
fruit = loadImage('/images/fruit.png');
for (let i = 0; i < 5; i++) {
fruit[i] = loadImage('/images/fruit.png');
}
}
function setup () {
createCanvas(window.innerWidth, window.innerHeight);
}
function draw () {
const selected = window.settings.selectedBrush
if (selected) {
const brush = window.brushes[selected]
brush.draw()
}
}
function windowResized () {
resizeCanvas(window.innerWidth, window.innerHeight);
}
For this, you’ll need the mousePressed() function to check if the user is pressing a mouse button.
After the user clicked, you need to check all your fruit brush images and detect if the mouse entered one of them. If so, change the current brush.
Are you drawing them currently?
Also you can think about what data you need to keep track in order to achieve that.
Are you comfortable with object oriented programming? Because it’s really going to help you when building your program
Note that in JavaScript, you don’t need to call window.something every time since the default scope is already the global window object so you can omit it.
The advantage is that let’s say you load an image as const img = createImg(...), then you can add a callback like img.mousePressed(function() {...}) which is triggered only if you click on the image (so you don’t have to test if the cursor is on the image or not).
Then you should load five different images. If you name the images fruit0.png to fruit4.png, you can use the loop variable, i, in the name of the file you’re loading.
Then you just need the index of the image that you’re drawing to change.
You code could just be:
PImage fruits = [];
int current_image = 0;
void setup(){
size(600,400);
for( int i = 0; i < 5; i++){
fruits[i] = loadImage("fruit" + i + ".png")
}
}
void draw(){
background(0);
image( fruits[current_image], 0, 0 );
}
void mousePressed(){
current_image++;
current_image %= fruits.length;
}