p5.js | createCheckbox() Function
The createCheckbox() function in p5.js is used to create a checkbox element in the DOM (Document Object Model). This function includes the p5.dom library. Add the following syntax in the head section.
html
Syntax:
createCheckbox(label, value)
Parameters:
- label: This parameter holds the label displayed beside the checkbox.
- value: This parameter holds the state of the checkbox (true/false).
Example: This example uses a checkbox to change the background color from light to dark and vice-versa.
javascript
// Create a variable for checkbox objectvar checkbox;// Create a function to change the background-colorfunction change_bg() { // Set dark color if box is checked if (this.checked()) { background("darkgreen"); } // Set light color if box is unchecked else { background("lightgreen"); }}function setup() { // Create a canvas createCanvas(400, 400); // Set the background-color background("lightgreen"); // Create a checkbox object // Initially unchecked checkbox = createCheckbox('Dark Background', false); // Posotion the checkbox object checkbox.position(160, 200); // Call the change_bg() function when the box // is checked or unchecked checkbox.changed(change_bg);} |
Output:
Before checking the box:

After checking the box:



