Welcome to the exciting world of generative art! In this tutorial, we'll embark on a creative journey using the power of p5.js, a beginner-friendly JavaScript library designed for creative coding. Whether you're an absolute beginner with no programming experience or a curious mind eager to explore the intersection of art and technology, you're in the right place.
Generative art involves the use of algorithms and code to create unique, often unpredictable, and mesmerizing visual compositions. Instead of traditional methods of creating art, generative art embraces the idea of letting the computer play an active role in the creative process. It's a fusion of programming logic and artistic expression, offering a canvas where creativity and computation come together.
This tutorial is designed with the absolute beginner in mind. We'll start by setting up the environment and gradually introduce you to fundamental concepts in a step-by-step manner. From drawing basic shapes to adding interactivity and animation, you'll gain hands-on experience and confidence in your creative coding abilities.
Even if you've never written a single line of code, don't worry! We'll guide you through each concept with clear explanations, examples, and exercises. By the end of this tutorial, you'll have created your own generative art piece and gained a foundation for further exploration in the exciting field of creative coding.
p5.js is a powerful and accessible library that makes creative coding with JavaScript accessible to everyone. It simplifies the complexities of programming, allowing you to focus on your artistic vision without getting bogged down in technical details. With p5.js, you can effortlessly create stunning visualizations, interactive experiences, and dynamic artworks, even if you've never written a line of code before.
So, let's dive in and unleash your creativity through the magic of generative art with p5.js! Get ready to transform your imagination into digital masterpieces.
So, let's dive in and unleash your creativity through the magic of generative art with p5.js! Get ready to transform your imagination into digital masterpieces.
The p5.js Editor is an online integrated development environment (IDE) specifically designed for creating projects with p5.js, a JavaScript library for creative coding and generative art. It provides a beginner-friendly platform where users can write, edit, and run p5.js sketches without the need for installing any software or dealing with complex configurations.
For a quick start, you can use the online p5.js Web Editor. It eliminates the need for local setup, making it perfect for beginners.
Navigate to p5.js Web Editor.
Click on “File” Then “New” to start a new project.
Copy and replace this code to web editor and press run button. Don't Worry, nothing you missed. This is a test.
function setup() {
createCanvas(400, 400);
background(220);
}
function draw() {
ellipse(width / 2, height / 2, 50, 50);
}
You should see a canvas with a circle in the center.
Congratulations! You've successfully set up your environment for generative art with p5.js. Now, let's move on to the exciting world of creative coding.
Welcome to the world of programming! In this section, we'll explore some basic programming concepts that form the backbone of generative art with p5.js. Even if you've never written code before, fear not – we'll take it step by step.
In programming, comments are notes within the code that are ignored by the computer. They are there to help you and others understand the code. In JavaScript (the language used with p5.js), comments start with //.
// This is a single-line comment
In addition to single-line comments (denoted by //), block comments (enclosed between /* and */) provide a way to add comments that span multiple lines.
Block comments are useful when you want to provide more detailed explanations or comment out a larger section of code.
/*
This is a block comment.
It can span multiple lines,
providing detailed explanations
about the code.
*/
// This is a single-line comment
Block comments are ignored by the computer just like single-line comments and serve as notes for programmers to understand the code better. Feel free to use them to add context, explanations, or to temporarily disable a section of your code.
Variables are containers for storing data. They have a name and can hold different types of information, like numbers or text. In p5.js, we use variables to control aspects of our artwork.
One of the exciting aspects of programming is the ability to experiment and see immediate results. Let's play around with the circleSize variable in the example above:
let circleSize = 30; // Declares a variable named circleSize with a value of 30
function setup() {
createCanvas(400, 400);
}
function draw() {
ellipse(200, 200, circleSize, circleSize);
}
Functions are blocks of reusable code that perform specific tasks. In p5.js, you'll use functions to create and control your generative art. Functions have a name followed by parentheses ().
function setup() {
// Code inside setup runs once at the beginning
}
function draw() {
// Code inside draw runs continuously in a loop
}
Loops allow you to repeat a block of code multiple times. In p5.js, the for loop is commonly used. It has three parts: initialization, condition, and iteration.
Result:
ellipse is a function to draw an unformed circle. don't worry, I will explain it later. copy and paste the line to get a run.
function setup() {
createCanvas(400, 400);
}
function draw() {
for (let i = 0; i < 5; i++) {
ellipse(50 + i * 80, 200, 50, 50);
}
}
By playing around with loop conditions and the code inside the loop, you can create diverse and visually captivating patterns. Loops are a fantastic way to introduce repetition and symmetry to your generative art. Enjoy experimenting and discovering the endless possibilities that loops bring to your creative coding journey!
Adjust the condition in the loop (i < 5) to control how many circles are drawn. Try increasing or decreasing the number.
Result:
Explore nested loops to create grid-like patterns. For example, use two loops to draw circles in rows and columns. A loop inside another loop!
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 3; j++) {
ellipse(100 + i * 80, 50 + j * 80, 50, 50);
}
}
Result:
Conditionals are used to make decisions in your code. The if statement is a common way to check if a condition is true, and then execute specific code.
Conditionals help your program make decisions. The if statement is a common conditional structure. It checks if a certain condition is true and executes a block of code accordingly.
We will learn more about conditions.
This code sets up a canvas, draws either a rectangle or an ellipse at the center of the canvas based on the position of the mouse. The comments provide explanations for each significant step in the code.
Run and check how it works!
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Set the drawing mode for rectangles
// to be drawn from their center
rectMode(CENTER);
// Check if the mouse is on the left or
//right half of the canvas
if (mouseX < width / 2) {
// If on the left, draw a rectangle
//at the center with a size of 50x50
rect(200, 200, 50, 50);
} else {
// If on the right, draw an ellipse
//at the center with a size of 50x50
ellipse(200, 200, 50, 50);
}
}
The random() function in p5.js generates random numbers. This is great for introducing unpredictability and variety into your generative art.
I Will explain Randomness at next sections.
Results:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
noLoop();
for (let x = 0; x < width; x+=30)
for (let y = 0; y < height; y+=30){
let randomSize = random(10, 30);
ellipse(x, y, randomSize);
}
}
Read and Try the code:
background(220) sets the background color to a light gray shade.
noLoop() stops the draw() function from continuously executing, making it.
Two nested loops (for loops) iterate through the canvas in increments of 30 pixels in both the horizontal (x) and vertical (y) directions.
Inside the nested loops, random(10, 30) generates a random number between 10 and 30, representing the size of each ellipse.
ellipse(x, y, randomSize) draws an circle at the current grid position (x, y) with the random size.
This code creates a visually interesting grid of randomly sized ellipses, resulting in a dynamic and abstract pattern. Adjusting the loop increments or the range of random sizes can produce different visual effects.
These are the basic programming concepts you'll be using in your generative art journey with p5.js. Don't worry if they seem a bit overwhelming at first – we'll be using them in fun and creative ways as we move forward!
Now that your environment is set up, let's dive into the fundamental concepts that form the basis of generative art with p5.js. These concepts will serve as building blocks for your creative coding journey.
In p5.js, the canvas is a digital surface where you can draw shapes, colors, and patterns. It's like a blank sheet of paper waiting for your imagination to unfold. To set up your canvas, you use the createCanvas(width, height) function.
function setup() {
createCanvas(400, 400);
}
This code creates a canvas with a width of 400 pixels and a height of 400 pixels. Think of it as defining the size of your artistic universe.
Colors can make your art vibrant and expressive. Use fill() to set the fill color and stroke() to set the outline color (stroke color). Here's a quick example:
function draw() {
fill(255, 0, 0); // Set fill color to red
ellipse(200, 200, 50, 50);
}
This code fills the circle with a red color.
The canvas has a coordinate system that helps you navigate and position your drawings. In p5.js, the top-left corner of the canvas is the point (0, 0). As you move right, the x-coordinate increases, and as you move down, the y-coordinate increases.
Now that you have your canvas, it's time to add elements to it. p5.js provides functions like ellipse(), rect(), and line() to draw basic shapes. Let's start simple:
function draw() {
ellipse(200, 200, 50, 50);
}
This code draws a circle (ellipse) at coordinates (200, 200) with a diameter of 50 pixels.
Variables store information that can change. They allow your art to be dynamic and responsive. Consider this example:
let circleSize = 50;
function draw() {
ellipse(200, 200, circleSize, circleSize);
}
Now, you can easily control the size of your ellipse by changing the value of circleSize.
Now that you've set up your canvas, it's time to start bringing your creative ideas to life by drawing basic shapes in p5.js. This section will introduce you to fundamental functions that allow you to sketch various shapes on your canvas.
Let's begin with rectangles. The rect() function is your gateway to drawing these four-sided shapes. It takes four parameters: x and y coordinates of the top-left corner, and the width and height of the rectangle.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220); // Set the background color to light gray
fill(255, 0, 0); // Set the fill color to red
rect(50, 50, 100, 150); // Draw a red rectangle at (50, 50) with a width of 100 and height of 150
}
In this example, the canvas is 400 pixels by 400 pixels, and we've drawn a red rectangle on it. The fill() function sets the fill color for the shape.
For straight lines, use the line() function. It requires four parameters: the x and y coordinates of the start and end points of the line.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
stroke(255, 0, 0); // Set the stroke color to red
line(50, 50, 150, 150); // Draw a red line from (50, 50) to (150, 150)
}
Next up, ellipses! The ellipse() function lets you draw circles and ovals. Like rect(), it takes four parameters: x and y coordinates of the center, and the width and height of the ellipse.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0, 0, 255); // Set the fill color to blue
ellipse(200, 200, 80, 80); // Draw a blue circle at (200, 200) with a diameter of 80 pixels
}
This time, we've drawn a blue circle at the center of the canvas. The ellipse() function makes it easy to create smooth, rounded shapes.
Points, on the other hand, are drawn using the point() function, which takes the x and y coordinates of the point.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
stroke(0); // Set the stroke color to black
strokeWeight(10); // Set the stroke weight to 10 pixels
point(200, 200); // Draw a black point at (200, 200)
}
In this example, I've added the strokeWeight() function to set the thickness of the point's stroke. Feel free to adjust the stroke weight and color to experiment with different visual effects.
Now that you've mastered drawing basic shapes, it's time to bring your sketches to life with colors and styles in p5.js. This section will cover how to set colors, adjust stroke properties, and explore the vibrant possibilities of creative coding.
In p5.js, the fill() and stroke() functions are essential for adding color to your shapes.
The fill() function sets the interior color of shapes. It takes three parameters representing the RGB values (Red, Green, Blue) of the color.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(255, 120, 0); // Set fill color to red
rect(50, 50, 100, 150); // Draw a red rectangle
}
On the other hand, the stroke() function defines the color of the shape's outline or border.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0, 0, 255); // Set fill color to blue
stroke(255, 0, 0); // Set stroke color to red
ellipse(200, 200, 80, 80); // Draw a blue circle with a red outline
}
Beyond color, you can control the thickness of your shape's outline using the strokeWeight() function.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0, 255, 0); // Set fill color to green
stroke(255); // Set stroke color to white
strokeWeight(5); // Set stroke weight to 5 pixels
rect(50, 50, 100, 150);
// Draw a green rectangle with a white, thicker outline
}
Feel free to experiment with different color combinations, stroke weights, and styles. These functions give you the power to create visually stunning and dynamic artworks. In the upcoming sections, we'll delve into mouse and keyboard interactions to make your p5.js sketches even more engaging and interactive.
Congratulations on adding vibrant colors and styles to your p5.js sketches! Now, let's take your creations to the next level by incorporating mouse interaction. This section will guide you through making your sketches responsive to mouse movements and clicks, opening up a world of possibilities for interactive art.
In p5.js, the mouse plays a crucial role in creating interactive experiences. The built-in variables mouseX and mouseY track the current coordinates of the mouse cursor, allowing you to dynamically respond to its position.
Let's start by creating a simple sketch where a shape follows the mouse cursor. In this example, we'll use the ellipse() function to draw a circle that constantly follows the mouse.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(255, 0, 0); // Set fill color to red
ellipse(mouseX, mouseY, 50, 50);
// Draw a red circle at the mouse position
}
Run this code, and you'll see a red circle tracking your mouse movements across the canvas. This basic interaction adds a dynamic element to your artwork.
Click Interaction
Beyond tracking the mouse position, you can also check whether a mouse button is being pressed using the mouseIsPressed variable. This opens up possibilities for creating interactive elements triggered by mouse clicks.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0, 0, 255); // Set fill color to blue
if (mouseIsPressed) {
ellipse(200, 200, 80, 80);
// Draw a blue circle when the mouse is pressed
} else {
rect(50, 50, 100, 100);
// Draw a blue rectangle when the mouse is not pressed
}
}
Now, when you click and hold the mouse button, a blue circle appears. Release the mouse button, and a blue rectangle takes its place.
The examples provided are just the tip of the iceberg. Experiment with different shapes, colors, and conditions based on mouse interactions. Whether you're creating games, simulations, or interactive art pieces, understanding mouse interaction is a powerful tool in your creative coding toolkit.
In the upcoming sections, we'll explore keyboard interaction, allowing you to expand the interactivity of your p5.js sketches even further.
Now that you've added mouse interaction to your toolkit, let's further enhance your p5.js sketches by incorporating keyboard interaction. This section will guide you through the basics of using keyboard input to create dynamic and responsive art.
In addition to mouse-related interactions, p5.js allows you to capture and respond to keyboard events. The key functions for keyboard interaction are keyIsPressed and key.
Let's start with a simple example. The keyIsPressed variable is a Boolean that becomes true when any key on the keyboard is pressed. Combining this with the key variable, you can check which key is being pressed.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0, 255, 0); // Set fill color to green
if (keyIsPressed) {
if (key === 'A' || key === 'a') {
ellipse(200, 200, 80, 80); // Draw a green circle when the 'A' key is pressed
} else if (key === 'B' || key === 'b') {
rect(50, 50, 100, 100); // Draw a green rectangle when the 'B' key is pressed
}
}
}
In this example, when you press the 'A' key, a green circle appears, and when you press the 'B' key, a green rectangle is drawn.
The true power of creative coding lies in combining various forms of interaction. Experiment with integrating both mouse and keyboard events to create dynamic and engaging sketches.
In the upcoming sections, we'll explore animation, arrays, and objects, allowing you to further expand your creative coding skills with p5.js.
let shapeX = 50;
let shapeY = 50;
let shapeSize = 50;
let fillColor;
function setup() {
createCanvas(400, 400);
fillColor = color(0, 255, 0); // Initialize fill color to green
}
function draw() {
background(220);
// Draw a shape at the current mouse position
fill(fillColor);
rect(shapeX, shapeY, shapeSize, shapeSize);
// Check for keyboard input
if (keyIsPressed) {
if (key === 'A' || key === 'a') {
fillColor = color(255, 0, 0); // Change fill color to red when 'A' key is pressed
} else if (key === 'B' || key === 'b') {
fillColor = color(0, 0, 255); // Change fill color to blue when 'B' key is pressed
}
}
// Check for mouse interaction
if (mouseIsPressed) {
// Move the shape to the mouse position when mouse is clicked
shapeX = mouseX - shapeSize / 2;
shapeY = mouseY - shapeSize / 2;
}
}
Randomization is a powerful tool in p5.js that enables generative art, where algorithms play a key role in creating visually engaging and unpredictable outcomes. In this section, we'll delve into the random() function, discuss the concept of random seeds, and explore the profound impact of randomization on generative art.
In p5.js, the random() function generates random floating-point numbers between 0 (inclusive) and 1 (exclusive). It can be used to introduce variability into your sketches, making each iteration unique.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Generate random RGB values for fill color
fill(random(255), random(255), random(255));
ellipse(200, 200, 100, 100);
}
In this example, the random() function is used to randomize the RGB values for the fill color of an ellipse, creating a vibrant and dynamic visual effect.
A random seed is a starting point for the random number generator. Setting a specific seed ensures that the sequence of random numbers generated is predictable and reproducible. This is particularly useful when you want to recreate a specific randomized outcome.
function setup() {
createCanvas(400, 400);
randomSeed(42); // Set a specific random seed
}
function draw() {
background(220);
// Generate consistent random colors with the same seed
fill(random(255), random(255), random(255));
ellipse(200, 200, 100, 100);
}
By setting a random seed using randomSeed(42), for instance, the sequence of random numbers remains the same across runs, providing deterministic results.
Randomization is at the heart of generative art, where algorithms and chance come together to create unique, often unpredictable compositions. The controlled use of random functions allows artists and programmers to explore vast creative landscapes.
function setup() {
createCanvas(400, 400);
background(220);
}
function draw() {
stroke(random(255), random(255), random(255));
strokeWeight(random(1, 5));
line(random(width), random(height), random(width), random(height));
}
In this example, each frame draws a random colored line with a random stroke weight, resulting in a continuously evolving generative artwork.
Randomization empowers you to experiment with an infinite range of possibilities. By combining random functions, loops, and conditions, you can create mesmerizing patterns, intricate shapes, and dynamic animations. The unpredictable nature of randomization adds an element of surprise and excitement to your generative art.
As you continue your journey into creative coding with p5.js, embrace the randomness, and let it guide you towards unexpected and captivating results. The world of generative art awaits, filled with endless opportunities for exploration and expression.
Now that you have a solid understanding of mouse and keyboard interaction, let's introduce the concept of animation in p5.js. Animation allows you to create dynamic and moving visuals, adding an extra layer of engagement to your sketches.
In p5.js, the draw function is called repeatedly, creating the illusion of motion. By updating the position or properties of elements in the draw loop, you can achieve animations.
Let's start with a simple example that moves a shape across the canvas.
let shapeX = 50;
let shapeY = 200;
let speed = 2;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0, 255, 0); // Set fill color to green
rect(shapeX, shapeY, 50, 50);
// Move the shape to the right
shapeX += speed;
// Reset the shape's position when it goes off-screen
if (shapeX > width) {
shapeX = -50;
}
}
In this example, the draw function continuously updates the position of a green rectangle, creating a smooth horizontal animation.
The frameRate function allows you to control the speed of the animation by specifying the number of frames displayed per second.
function setup() {
createCanvas(400, 400);
frameRate(30); // Set the frame rate to 30 frames per second
}
function draw() {
background(220);
fill(0, 255, 0); // Set fill color to green
ellipse(frameCount % width, height / 2, 50, 50); // Move a circle horizontally
// Experiment with different formulas to create various animations
}
Combine your newfound knowledge of mouse and keyboard interaction with animation to create interactive experiences. You can change the animation based on user input, creating responsive and engaging visual effects.
In the upcoming sections, we'll explore more advanced topics such as arrays and objects, allowing you to create even more sophisticated and visually stunning p5.js sketches.
As you progress in your p5.js journey, understanding how to work with arrays and loops becomes essential. These concepts provide a structured way to manage and manipulate multiple elements in your sketches, opening up new possibilities for creativity and complexity.
An array is a collection of values that can be of any data type, including numbers, strings, or even other arrays. In p5.js, arrays are particularly useful for handling multiple objects or elements systematically.
let circles = [];
function setup() {
createCanvas(400, 400);
// Create an array of circles
for (let i = 0; i < 5; i++) {
circles[i] = {
x: random(width),
y: random(height),
diameter: random(20, 50),
fillColor: color(random(255), random(255), random(255))
};
}
}
function draw() {
background(220);
// Display each circle in the array
for (let i = 0; i < circles.length; i++) {
fill(circles[i].fillColor);
ellipse(circles[i].x, circles[i].y, circles[i].diameter);
}
}
In this example, an array circles is used to store information about multiple circles, and a loop is employed to display each circle on the canvas.
Loops in p5.js allow you to efficiently repeat a block of code, reducing redundancy and making your sketches more concise and readable.
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Draw multiple lines using a loop
for (let i = 0; i < 10; i++) {
stroke(random(255), random(255), random(255));
line(random(width), random(height), random(width), random(height));
}
}
Here, a loop is used to draw multiple random-colored lines on the canvas.
The true power emerges when you combine arrays and loops. This combination allows you to create dynamic and varied compositions with ease.
let circles = [];
function setup() {
createCanvas(400, 400);
// Create an array of circles
for (let i = 0; i < 5; i++) {
circles[i] = {
x: random(width),
y: random(height),
diameter: random(20, 50),
xSpeed: random(-2, 2),
ySpeed: random(-2, 2),
fillColor: color(random(255), random(255), random(255))
};
}
}
function draw() {
background(220);
// Move and display each circle in the array
for (let i = 0; i < circles.length; i++) {
circles[i].x += circles[i].xSpeed;
circles[i].y += circles[i].ySpeed;
fill(circles[i].fillColor);
ellipse(circles[i].x, circles[i].y, circles[i].diameter);
// Bounce off the edges
if (circles[i].x < 0 || circles[i].x > width) {
circles[i].xSpeed *= -1;
}
if (circles[i].y < 0 || circles[i].y > height) {
circles[i].ySpeed *= -1;
}
}
}
This example demonstrates an array of moving circles, each with its own speed and direction, creating a dynamic and visually interesting composition.
Arrays and loops provide a structured way to manage complexity in your p5.js sketches. Experiment with different data structures, iterate through arrays, and create loops that bring your ideas to life. As you continue to explore, you'll find that arrays and loops are indispensable tools for creating more sophisticated and interactive visual experiences.
As your creative coding journey unfolds, you'll encounter scenarios where the structure and behavior of your elements become more complex. This is where the concepts of objects and classes in p5.js come into play. Objects allow you to encapsulate data and functionality into cohesive units, providing a modular and organized approach to your sketches.
An object in p5.js is a self-contained unit that encapsulates both data (properties) and functions (methods) related to a specific entity or element. Using objects helps organize your code and enables you to create multiple instances of the same structure with varying properties.
let ball;
function setup() {
createCanvas(400, 400);
// Create a ball object
ball = {
x: width / 2,
y: height / 2,
diameter: 50,
xSpeed: 2,
ySpeed: -1,
color: color(255, 0, 0),
// Display the ball
display: function() {
fill(this.color);
ellipse(this.x, this.y, this.diameter);
},
// Move the ball
move: function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
// Bounce off the edges
if (this.x < 0 || this.x > width) {
this.xSpeed *= -1;
}
if (this.y < 0 || this.y > height) {
this.ySpeed *= -1;
}
}
};
}
function draw() {
background(220);
// Use the methods of the ball object
ball.move();
ball.display();
}
In this example, the ball object encapsulates its properties (position, speed, color) and functionality (display and move methods). This makes the code more modular and scalable.
Classes: Blueprints for Objects
Classes in p5.js provide a blueprint for creating objects with similar properties and methods. Defining a class allows you to instantiate multiple objects of the same type while keeping the code organized.
class Ball {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.diameter = 50;
this.xSpeed = 2;
this.ySpeed = -1;
this.color = color(255, 0, 0);
}
display() {
fill(this.color);
ellipse(this.x, this.y, this.diameter);
}
move() {
this.x += this.xSpeed;
this.y += this.ySpeed;
// Bounce off the edges
if (this.x < 0 || this.x > width) {
this.xSpeed *= -1;
}
if (this.y < 0 || this.y > height) {
this.ySpeed *= -1;
}
}
}
let ball;
function setup() {
createCanvas(400, 400);
// Create an instance of the Ball class
ball = new Ball();
}
function draw() {
background(220);
// Use the methods of the Ball class
ball.move();
ball.display();
}
Here, the Ball class defines the structure and behavior of a ball object. The ball variable is an instance of this class, allowing you to create and manipulate multiple balls easily.
As your sketches become more intricate, objects and classes become essential tools. You can create complex scenes, interactive elements, and dynamic animations by combining the power of objects, arrays, loops, and more. Experiment, iterate, and embrace the versatility of objects in p5.js to elevate your creative coding projects.
Enhance your creative coding experience by incorporating images and sound into your p5.js sketches. These multimedia elements add depth, interactivity, and a multi-sensory dimension to your creations.
p5.js provides functions for loading and displaying images. You can use your own image files or explore the variety of images available through online resources.
let img;
function preload() {
// Load an image before the sketch starts
img = loadImage('path/to/your/image.jpg');
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Display the loaded image
image(img, 50, 50, 300, 300);
}
In this example, the preload() function ensures that the image is loaded before the sketch starts. The image() function is then used to display the image on the canvas.
p5.js allows you to play and manipulate audio in your sketches. You can use sound files or generate tones dynamically.
let sound;
function preload() {
// Load a sound file before the sketch starts
sound = loadSound('path/to/your/sound.mp3');
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
}
function mousePressed() {
// Play the loaded sound when the mouse is pressed
sound.play();
}
Here, the preload() function loads a sound file, and the mousePressed() function plays the sound when the mouse is clicked.
Adding images and sounds to your p5.js sketches opens up a vast array of creative possibilities. Whether you're creating interactive games, visualizations, or multimedia art, the integration of images and sounds brings richness and depth to your projects. Explore different media, experiment with effects, and let your imagination guide you in crafting unique and captivating experiences.
Creating sketches that adapt to different screen sizes and orientations is crucial for providing a seamless and enjoyable user experience. In this section, we'll explore techniques for making your p5.js sketches responsive and adaptable to various devices.
p5.js provides functions to dynamically adjust the canvas size based on the dimensions of the browser window.
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(220);
// Your drawing code goes here
}
function windowResized() {
// Resize the canvas when the window is resized
resizeCanvas(windowWidth, windowHeight);
}
In this example, the windowResized() function is triggered whenever the window is resized, allowing the canvas to be dynamically resized to fit the new dimensions.
Consider adjusting your sketch based on the orientation of mobile devices, providing a more tailored experience.
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(220);
// Your drawing code goes here
}
function windowResized() {
// Resize the canvas when the window is resized
resizeCanvas(windowWidth, windowHeight);
}
function deviceTurned() {
// Handle changes in device orientation (portrait/landscape)
if (rotationX === 0) {
// Portrait orientation
} else {
// Landscape orientation
}
}
The deviceTurned() function is called when the device changes orientation, allowing you to adjust your sketch accordingly.
Use media queries in your HTML and CSS to apply specific styles or behaviors based on the screen size or other characteristics of the device.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
canvas {
display: block;
margin: 0 auto;
}
@media only screen and (max-width: 600px) {
canvas {
background-color: lightblue;
}
}
</style>
<script src="p5.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
In this example, the CSS includes a media query that changes the background color of the canvas when the screen width is less than or equal to 600 pixels.
Consider designing your sketches with accessibility in mind. Ensure that your content is perceivable, operable, and understandable for users with different abilities.
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(220);
// Your drawing code goes here
}
function keyPressed() {
// Add accessibility features, e.g., text-to-speech
if (key === 'A' || key === 'a') {
speak('You pressed the A key.');
}
}
function speak(message) {
// Use text-to-speech to read the message
let speech = new SpeechSynthesisUtterance(message);
speechSynthesis.speak(speech);
}
In this example, the keyPressed() function includes an accessibility feature by triggering text-to-speech when the 'A' key is pressed.
Designing responsive and accessible p5.js sketches ensures that your creative work is inclusive and enjoyable across a diverse range of devices and user abilities. Experiment with these techniques, adapt them to your specific needs, and embrace the principles of user-centric design as you continue to create engaging and accessible interactive experiences.
Visual art is inherently subjective; each person perceives it differently. When creating visual art, you’re crafting a unique experience for every viewer. Generative art takes this a step further by making visual arts more dynamic and varied.
Imagine you want to depict a river that conveys feelings of stress and anger. Here’s how you can approach it:
Instead of drawing a realistic river, which limits the viewer’s interpretation and is challenging for generative art, abstract the concept. Think about what elements of a river might evoke stress and anger. For instance, a river with hard, jagged edges can symbolize anger.
At this level of abstraction, the river is represented in 2D. Focus on shapes and forms that convey the desired emotions. Hard edges and chaotic lines can suggest turmoil and stress.
Colors play a crucial role in evoking emotions. Use a palette dominated by reds, yellows, and oranges to convey anger. Contrasting these with black and white can enhance the chaotic feel. The interplay of these colors with hard-edged lines can intensify the viewer’s sense of stress and anger. Here I can see some variations. But it's better to make variation in shapes.
It's not exactly what I asked DALL-E 3 for, but it sparked a great idea for my next piece of art (that I'll never create 😂)
By abstracting the river and carefully choosing shapes and colors, you can create a generative art piece that dynamically expresses the emotions you want to convey.
function setup() {
//creating canvas and make it ready for art
createCanvas(400, 600);
background(220);
noLoop();
}
function draw() {
//let's draw river at first
//select a random point on top of screen to start river
let riverStartPoint=createVector(random(width),0);
}
Certainly! Let’s dive deeper into the riverStartPoint:
createVector(random(width), 0): This line creates a vector, which is essentially a point in 2D space, using the createVector function.
random(width): This part generates a random number between 0 and the width of the canvas (400 pixels in this case). This random number determines the x-coordinate of the starting point of our river.
0: This is the y-coordinate of the starting point, which is fixed at the top of the canvas.
So, riverStartPoint is a point with a random x-coordinate along the top edge of the canvas. This point will be used as the starting location for drawing the river. By randomizing the x-coordinate, each time the code runs, the river will start from a different position, adding variety to the artwork.
function draw() {
//let's draw river at first
//select a random point on top of screen to start river
let riverStartPoint=createVector(random(width),0);
//drawing the river slowly from top to down of canvas.
//we leave everything randomized, but controlling it!
let nextPoint1=createVector(riverStartPoint.x + random(-50,50),100);
//let's draw a line from start point to the new point.
line(riverStartPoint.x,riverStartPoint.y, nextPoint1.x,nextPoint1.y);
//let's draw other side of river
let nextPoint2=createVector(riverStartPoint.x + random(-50,50),100);
line(riverStartPoint.x,riverStartPoint.y, nextPoint2.x,nextPoint2.y);
}
Let’s break down the two new lines in the draw function:
let nextPoint1 = createVector(riverStartPoint.x + random(-50, 50), 100);
createVector(riverStartPoint.x + random(-50, 50), 100): This creates a new point (nextPoint1) with:
x-coordinate: A random value between -50 and 50 added to the x-coordinate of riverStartPoint. This randomization makes the river meander.
y-coordinate: Fixed at 100 pixels down from the top of the canvas.
This point represents the next position in the river’s path, creating a sense of flow and randomness.
line(riverStartPoint.x, riverStartPoint.y, nextPoint1.x, nextPoint1.y);
line(riverStartPoint.x, riverStartPoint.y, nextPoint1.x, nextPoint1.y): This draws a line from riverStartPoint to nextPoint1.
This line segment is the first part of the river, connecting the starting point to the next point.
let nextPoint2 = createVector(riverStartPoint.x + random(-50, 50), 100);
Similar to nextPoint1, this creates another point (nextPoint2) with:
x-coordinate: A random value between -50 and 50 added to the x-coordinate of riverStartPoint.
y-coordinate: Fixed at 100 pixels down from the top of the canvas.
This point represents another part of the river’s path, adding more variation.
line(riverStartPoint.x, riverStartPoint.y, nextPoint2.x, nextPoint2.y);
This draws another line from riverStartPoint to nextPoint2.
This line segment represents the other side of the river, creating a more complex and natural-looking river path.
These lines help create a randomized, flowing river effect by drawing lines from the starting point to two new points, making the river appear more natural and dynamic.
Sorry, I'm writing right now. it's a long tutorial, we have generative art concepts in resume and more advance codings.
here is the start of generative art!