実例 Conditions

Conditions

If and else statements allow a block of code to run only when a certain condition is true. This example only animates when the mouse is held down. This is because of the if statement on line 59. You can read more about if and else statements in the p5 reference or on MDN.

Comparison operators help to form conditions by comparing two values. In this example, the hue of the circle resets to zero when the hue is at least 360 because of the if statement on line 69. You can read more about comparison operators on MDN.

Logical operators allow conditions to be combined. && checks that both conditions are true. The circle in this example has a black fill when it is toward the horizontal center of the canvas, and it has a white fill when it is not. This is because of the if statement on line 45, which checks that the circle’s x position is at least 100 and also no more than 300. || checks that at least one of the conditions is true. The circle reverses horizontal speed when it reaches the left or right edge of the canvas because of the if statement on line 75.