Variables
Variables in P5JS are used to store and manipulate data. They are essential for creating interactive and dynamic sketches.
With variables, you can store numbers, strings, booleans, and more. They allow you to keep track of changing values and make your code more flexible and reusable.
To declare a variable in P5JS, you can use the let
keyword followed by the variable name. For example, let x = 10;
creates a variable named x
and assigns it the value of 10.
You can then use variables in your code to perform calculations, update positions, change colors, and much more.
Art Editor
In this tutorial we will use the https://editor.p5js.org
It's a free online p5js editor that will work to render almost every code you can make.
Preview
Example
let x = 100; // X position
let y = 200; // Y position
let bgColor = "#9E9E9E"; // Background color
let ellipseColor = "#FF0303" // Ellipse color
function setup() {
createCanvas(400, 400);
}
function draw() {
background(bgColor) // Set the background color using the previously saved color
fill(ellipseColor); // Fill color using the previously saved color
ellipse(x, y, 50, 50); // Draw a circle at (x, y) previously defined
}
Preview
Deep Learn
If you want to deep learn variables you can check Mozilla Docs and W3Schools to learn more about JavaScript Variables.
- Mozilla Docs - Storing the information you need — Variables
- W3Schools - JavaScript Variables