This can be expanded with the keyword “else” to include code that is executed if the conditional expression is false. This is the equivalent of “otherwise, do such and such.”
We can eliminate the rect in our code above by using IF ELSE and only background and no fill. See the example below:
1 2 3 4 5 6 7 8 9 10 11 | function setup() { createCanvas(windowWidth, windowHeight); } function draw() { if (mouseX < windowWidth/2) { background(255); } else { background(0); } } |
Pay attention to the format and do not forget the importance of the opening and closing curly brackets { } throughout. Indenting your code in the same style as the example also helps your code be readable. If the same code is written as follows:
1 2 3 4 5 6 7 8 9 10 11 | function setup() { createCanvas(windowWidth, windowHeight); } function draw() { if (mouseX < windowWidth/2) { background(255); } else { background(0); } } |
it becomes much harder to see where the conditionals are. Don’t write code that way. Always indent your code nicely.
Complete Activity 17