p5.js createCheckbox() Function
Last Updated :
16 Aug, 2023
Improve
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.
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js">
</script>
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.
// Create a variable for checkbox object
var checkbox;
// Create a function to change the background-color
function 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);
// Position 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:

Reference: https://p5js.org/reference/#/p5/createCheckbox