p5.js

p5.js is a JavaScript library that simplifies the process of creating interactive graphics and animations in the browser. It provides a set of functions and utilities that enable developers to easily manipulate HTML elements, create 2D and 3D graphics, handle user input, and create animations.

With p5.js, you can create visual and interactive experiences by writing code that responds to user actions and updates the display in real-time. It abstracts away many of the complexities of web development, allowing developers to focus on the creative aspects of their projects.

p5.js follows a simple setup-draw loop structure. The setup() function is called once at the beginning of the program and is typically used to set up the canvas and initialize any variables. The draw() function is called repeatedly in a loop and is where you define the main logic of your program, updating the display with each iteration.

p5.js provides a wide range of functions for drawing shapes, manipulating colors, handling user input (e.g., mouse and keyboard events), loading and displaying images and videos, working with sound, and much more. It also includes libraries for additional functionality, such as creating physics simulations or working with machine learning.

Overall, p5.js makes it easy to create interactive and dynamic visual experiences on the web, making it a popular choice for artists, designers, educators, and beginners interested in creative coding.

p5.js provides a wide range of capabilities for creating interactive graphics and animations on the web. Some of its key features include:

  1. Drawing Shapes and Colors: p5.js offers functions for drawing various shapes such as rectangles, circles, lines, polygons, and curves. You can customize the stroke and fill colors, adjust stroke weight, and work with transparency.
  2. Animation and Interactivity: With p5.js, you can create animations by continuously updating the display within the draw() function. It supports smooth transitions, frame rate control, and easing functions. You can also respond to user input, including mouse and keyboard events, and create interactive elements.
  3. 2D and 3D Graphics: p5.js supports both 2D and 3D graphics. It provides functions for working with 3D geometries, applying transformations, and rendering 3D objects. You can create 3D scenes, work with lights and cameras, and apply textures and materials to objects.
  4. Image and Video Processing: p5.js allows you to load, manipulate, and display images and videos. You can apply filters, adjust colors, crop and resize images, and create video players. It also provides access to webcams and allows you to capture video and images in real-time.
  5. Sound and Audio: p5.js includes a sound library that enables you to play, control, and manipulate audio. You can load and play sound files, generate tones and waveforms, apply effects, and analyze audio data.
  6. Input and Interaction: p5.js provides functions for working with user input, including mouse and keyboard events. You can detect mouse clicks, track mouse movement, handle keyboard input, and create interactive buttons, sliders, and other UI elements.
  7. Text and Typography: p5.js supports text rendering, allowing you to display and manipulate text on the canvas. You can set the font, size, alignment, and color of text, and apply text effects such as rotation, scaling, and skewing.
  8. Data Visualization: p5.js can be used for data visualization. It offers functions for creating charts, graphs, and other visual representations of data. You can work with arrays, objects, and JSON data, and visualize data using bar graphs, pie charts, scatter plots, and more.
  9. External Libraries and APIs: p5.js supports the integration of external libraries and APIs, allowing you to extend its capabilities. There are numerous p5.js libraries available for specific purposes, such as physics simulations, computer vision, machine learning, and more.
  10. Cross-platform and Web-Based: p5.js runs on web browsers and is compatible with various operating systems. It provides a simple and accessible platform for creating interactive web-based projects that can be easily shared and distributed.

These are just some of the capabilities of p5.js. With its extensive documentation, vibrant community, and active development, p5.js continues to evolve and expand its functionality, empowering creators to explore and express their ideas through interactive visual experiences.

Usage

To use p5.js code in a web page, you need to include the p5.js library and write your p5.js code within the appropriate JavaScript tags. Here’s a step-by-step guide:

  1. Download the p5.js library: Visit the p5.js website (https://p5js.org/) and download the p5.js library. You can choose between the minified or non-minified version depending on your needs.
  2. Include the p5.js library in your HTML file: Add the following script tag within the <head> section of your HTML file, pointing to the location where you saved the p5.js library:
http://path/to/p5.js
  <style>body {padding: 0; margin: 0;} canvas {vertical-align: top;}</style>
</head>
<body>
  http://sketch.js
</body>
</html>

Make sure to save the p5.js code in a separate JavaScript file, such as sketch.js, and include it in the HTML file using a <script> tag as shown above.

That’s it! When you open your HTML file in a browser, you should see the image displayed on the canvas.

Stick man

Here’s an example of p5.js code that draws a stick figure (stick man) on a canvas:

javascriptCopy codefunction setup() {
  // Create a canvas
  createCanvas(400, 400);
}

function draw() {
  // Set the background color
  background(220);

  // Draw the stick figure
  drawStickMan(width / 2, height / 2, 100);
}

function drawStickMan(x, y, size) {
  // Set the stroke weight and color
  strokeWeight(4);
  stroke(0);

  // Draw the head
  let headSize = size / 4;
  ellipse(x, y - size / 2, headSize, headSize);

  // Draw the body
  line(x, y - size / 2 + headSize / 2, x, y + size / 2);

  // Draw the arms
  line(x - size / 2, y, x + size / 2, y);
  line(x - size / 2, y, x - size / 4, y - size / 4);
  line(x + size / 2, y, x + size / 4, y - size / 4);

  // Draw the legs
  line(x, y + size / 2, x - size / 4, y + size);
  line(x, y + size / 2, x + size / 4, y + size);
}

In this code, the setup() function creates a canvas, and the draw() function is continuously called to draw the stick figure using the drawStickMan() function.

The drawStickMan() function takes three parameters: x and y coordinates of the stick figure’s center, and size to determine the overall size of the figure. The figure is drawn using p5.js functions like ellipse() to draw the head, line() to draw the body, arms, and legs.

You can adjust the values in the drawStickMan() function to modify the size and proportions of the stick figure. Additionally, you can add more p5.js drawing functions or change the stroke weight and color to customize the appearance of the stick figure.

Remember to include the p5.js library in your HTML file as explained in the previous response.

When you open your HTML file in a browser, you should see the stick figure drawn on the canvas.

Draw a Pig

Here’s an example of p5.js code that draws a simple representation of a pig:

function setup() {
  // Create a canvas
  createCanvas(400, 400);
}

function draw() {
  // Set the background color
  background(220);

  // Draw the pig
  drawPig(width / 2, height / 2, 100);
}

function drawPig(x, y, size) {
  // Set the stroke weight and color
  strokeWeight(2);
  stroke(0);

  // Draw the head
  fill(255, 182, 193);
  ellipse(x, y - size / 2, size * 0.8, size * 0.8);

  // Draw the ears
  fill(255, 182, 193);
  ellipse(x - size * 0.35, y - size * 0.75, size * 0.3, size * 0.3);
  ellipse(x + size * 0.35, y - size * 0.75, size * 0.3, size * 0.3);

  // Draw the eyes
  fill(0);
  ellipse(x - size * 0.2, y - size * 0.3, size * 0.15, size * 0.15);
  ellipse(x + size * 0.2, y - size * 0.3, size * 0.15, size * 0.15);

  // Draw the nose
  fill(0);
  ellipse(x, y - size * 0.1, size * 0.1, size * 0.1);

  // Draw the body
  fill(255, 182, 193);
  ellipse(x, y + size * 0.2, size, size * 0.8);

  // Draw the legs
  fill(255, 182, 193);
  ellipse(x - size * 0.35, y + size * 0.4, size * 0.3, size * 0.6);
  ellipse(x + size * 0.35, y + size * 0.4, size * 0.3, size * 0.6);

  // Draw the tail
  fill(255, 182, 193);
  ellipse(x + size * 0.5, y + size * 0.1, size * 0.2, size * 0.2);
}

In this code, the setup() function creates a canvas, and the draw() function is continuously called to draw the pig using the drawPig() function.

The drawPig() function takes three parameters: x and y coordinates of the pig’s center, and size to determine the overall size of the pig. The pig is drawn using p5.js functions like ellipse() to draw the head, ears, eyes, nose, body, legs, and tail.

You can adjust the values in the drawPig() function to modify the size and proportions of the pig. Additionally, you can add more p5.js drawing functions or change the fill and stroke colors to customize the appearance of the pig.

Make sure to include the p5.js library in your HTML file as explained in the previous responses. When you open your HTML file in a browser, you should see a simple representation of a pig drawn on the canvas.

Draw some emojis

Here’s an example of p5.js code that draws a grid of emojis:

javascriptCopy codelet emojiSize = 50; // Size of each emoji
let numRows = 4; // Number of rows in the grid
let numCols = 4; // Number of columns in the grid

function setup() {
  // Create a canvas
  createCanvas(400, 400);
}

function draw() {
  // Set the background color
  background(220);

  // Draw the grid of emojis
  drawEmojiGrid();
}

function drawEmojiGrid() {
  // Loop through each row and column
  for (let row = 0; row < numRows; row++) {
    for (let col = 0; col < numCols; col++) {
      // Calculate the position of the current emoji
      let x = col * emojiSize + emojiSize / 2;
      let y = row * emojiSize + emojiSize / 2;

      // Draw the emoji
      drawEmoji(x, y);
    }
  }
}

function drawEmoji(x, y) {
  // Set the emoji characteristics
  textSize(emojiSize);
  textAlign(CENTER, CENTER);

  // Draw the emoji
  text("😊", x, y);
}

In this code, the setup() function creates a canvas, and the draw() function is continuously called to draw the grid of emojis using the drawEmojiGrid() function.

The drawEmojiGrid() function loops through each row and column in the grid specified by numRows and numCols. For each position in the grid, it calculates the x and y coordinates based on the current row and column, and then calls the drawEmoji() function to draw an emoji at that position.

The drawEmoji() function sets the size and alignment of the emoji using textSize() and textAlign() functions, and then uses the text() function to draw the emoji itself. In this example, the emoji used is “😊”, but you can replace it with any other emoji of your choice.

You can adjust the emojiSize, numRows, and numCols variables to modify the size and dimensions of the grid and the emojis within it.

Remember to include the p5.js library in your HTML file as explained in the previous responses. When you open your HTML file in a browser, you should see a grid of emojis displayed on the canvas.

Draw a Tesseract

Drawing a hypercube (also known as a tesseract) in 3D space is a complex task. However, we can create a 2D representation of a hypercube by projecting it onto the canvas. Here’s an example of p5.js code that draws a 2D representation of a hypercube:

let angle = 0;
let rotationSpeed = 0.01;

function setup() {
  // Create a canvas
  createCanvas(400, 400);
}

function draw() {
  // Set the background color
  background(220);

  // Translate the origin to the center of the canvas
  translate(width / 2, height / 2);

  // Rotate the hypercube
  rotateX(angle);
  rotateY(angle);

  // Set the stroke weight and color
  strokeWeight(2);
  stroke(0);

  // Draw the hypercube
  drawHypercube(100);

  // Update the rotation angle
  angle += rotationSpeed;
}

function drawHypercube(size) {
  // Define the vertices of the hypercube
  let vertices = [];
  for (let i = -1; i <= 1; i += 2) {
    for (let j = -1; j <= 1; j += 2) {
      for (let k = -1; k <= 1; k += 2) {
        for (let l = -1; l <= 1; l += 2) {
          vertices.push(createVector(i * size / 2, j * size / 2, k * size / 2, l * size / 2));
        }
      }
    }
  }

  // Connect the vertices to form the hypercube
  for (let i = 0; i < vertices.length; i++) {
    for (let j = i + 1; j < vertices.length; j++) {
      connectVertices(vertices[i], vertices[j]);
    }
  }
}

function connectVertices(v1, v2) {
  line(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z);
}

In this code, the setup() function creates a canvas, and the draw() function is continuously called to draw the hypercube.

Inside the draw() function, we translate the origin to the center of the canvas using translate(). Then, we rotate the hypercube around the X and Y axes using rotateX() and rotateY() based on the angle variable. The strokeWeight() and stroke() functions set the stroke weight and color for drawing the lines.

The drawHypercube() function defines the vertices of the hypercube and connects them using the connectVertices() function. The connectVertices() function draws a line between two vertices.

You can adjust the size of the hypercube by modifying the size parameter in the drawHypercube() function. Additionally, you can change the rotation speed by modifying the rotationSpeed variable in the draw() function.

Remember to include the p5.js library in your HTML file as explained in the previous responses. When you open your HTML file in a browser, you should see a 2D representation of a hypercube rotating on the canvas.

Draw Elevations

To draw the top, side, and front elevations of a cube tilted at a 45-degree angle to the left, you can create three separate p5.js functions for each elevation. Here’s an example code:

function setup() {
  // Create a canvas
  createCanvas(400, 400);
}

function draw() {
  // Set the background color
  background(220);

  // Draw the top elevation
  drawTopElevation(width / 2, height / 2, 100);

  // Draw the side elevation
  drawSideElevation(width / 2 + 150, height / 2, 100);

  // Draw the front elevation
  drawFrontElevation(width / 2 - 150, height / 2, 100);
}

function drawTopElevation(x, y, size) {
  // Set the stroke weight and color
  strokeWeight(2);
  stroke(0);

  // Draw the top square
  rect(x, y - size, size, size);

  // Draw the connecting lines
  line(x, y - size, x + size / 2, y - size / 2);
  line(x + size, y - size, x + size / 2, y - size / 2);
  line(x + size, y, x + size / 2, y - size / 2);
}

function drawSideElevation(x, y, size) {
  // Set the stroke weight and color
  strokeWeight(2);
  stroke(0);

  // Draw the side square
  rect(x, y - size, size, size);

  // Draw the connecting lines
  line(x + size, y - size, x + size, y);
  line(x + size, y, x + size / 2, y - size / 2);
  line(x, y - size, x, y);
  line(x, y, x + size / 2, y - size / 2);
}

function drawFrontElevation(x, y, size) {
  // Set the stroke weight and color
  strokeWeight(2);
  stroke(0);

  // Draw the front square
  rect(x, y - size, size, size);

  // Draw the connecting lines
  line(x + size, y - size, x + size, y);
  line(x, y - size, x, y);
  line(x + size, y, x, y);
}

In this code, the setup() function creates a canvas, and the draw() function is continuously called to draw the three elevations: top, side, and front.

Each elevation is drawn using a separate function: drawTopElevation(), drawSideElevation(), and drawFrontElevation(). These functions take three parameters: x and y coordinates of the elevation’s center, and size to determine the size of the cube.

Inside each elevation function, we set the stroke weight and color using strokeWeight() and stroke() functions. Then, we draw a square using rect() function and connect the corners of the square with lines using line() function to represent the tilted cube in each elevation.

You can modify the size parameter in each elevation function to adjust the size of the cube. Additionally, you can change the stroke weight and color to customize the appearance of the elevations.

Make sure to include the p5.js library in your HTML file as explained in the previous responses. When you open your HTML file in a browser, you should see the top, side, and front elevations of a cube tilted at a 45

Draw A Spinning Cubes

Here’s an example of p5.js code that draws animation frames of a rotating cube:

let angle = 0;
let rotationSpeed = 0.01;

function setup() {
  // Create a canvas
  createCanvas(400, 400, WEBGL);
}

function draw() {
  // Set the background color
  background(220);

  // Set the rotation angle
  angle += rotationSpeed;

  // Apply rotation transformations
  rotateX(angle);
  rotateY(angle);

  // Draw the rotating cube
  drawCube(100);
}

function drawCube(size) {
  // Set the stroke weight and color
  strokeWeight(2);
  stroke(0);

  // Draw the front face
  fill(255);
  square(-size / 2, -size / 2, size);

  // Draw the back face
  fill(200);
  square(-size / 2, -size / 2, -size);

  // Draw the top face
  fill(150);
  beginShape();
  vertex(-size / 2, -size / 2, -size);
  vertex(size / 2, -size / 2, -size);
  vertex(size / 2, -size / 2, size);
  vertex(-size / 2, -size / 2, size);
  endShape(CLOSE);

  // Draw the bottom face
  fill(100);
  beginShape();
  vertex(-size / 2, size / 2, -size);
  vertex(size / 2, size / 2, -size);
  vertex(size / 2, size / 2, size);
  vertex(-size / 2, size / 2, size);
  endShape(CLOSE);

  // Draw the left face
  fill(50);
  beginShape();
  vertex(-size / 2, -size / 2, -size);
  vertex(-size / 2, size / 2, -size);
  vertex(-size / 2, size / 2, size);
  vertex(-size / 2, -size / 2, size);
  endShape(CLOSE);

  // Draw the right face
  fill(0);
  beginShape();
  vertex(size / 2, -size / 2, -size);
  vertex(size / 2, size / 2, -size);
  vertex(size / 2, size / 2, size);
  vertex(size / 2, -size / 2, size);
  endShape(CLOSE);
}

In this code, the setup() function creates a canvas with the WEBGL renderer, allowing us to work in 3D space. The draw() function is continuously called to draw the animation frames of the rotating cube.

Inside the draw() function, we update the rotation angle angle based on the rotationSpeed variable. We then apply rotation transformations using rotateX() and rotateY() functions to rotate the cube.

The drawCube() function is responsible for drawing the cube. It uses the fill() function to set the fill color for each face of the cube and the square() function to draw the front and back faces. For the top, bottom, left, and right faces, we use the beginShape() and endShape() functions to define the vertices and draw the faces as polygons.

You can adjust the size parameter in the drawCube() function to modify the size of the cube. Additionally, you can change the fill colors and stroke weight to customize the appearance of the cube.

Make sure to include the p5.js library

Advanced uses

p5.js is a versatile library that allows for advanced and creative uses beyond the basics. Here are some examples of advanced applications and uses of p5.js:

  1. Game Development: You can create complex games using p5.js. With its animation capabilities, user input handling, collision detection, and sound support, p5.js can be used to build 2D games, including platformers, puzzles, simulations, and more.
  2. Creative Coding and Generative Art: p5.js is often used for creative coding and generative art projects. By combining algorithms, randomness, and user input, you can create visually stunning and interactive art pieces that generate unique visuals, patterns, and animations.
  3. Data Visualization and Information Design: p5.js provides powerful tools for visualizing data and creating interactive information design projects. You can create dynamic and interactive charts, graphs, maps, and visual representations of complex data sets, allowing users to explore and understand information in a visual and engaging way.
  4. Virtual and Augmented Reality (VR/AR): p5.js has libraries and extensions that enable the creation of virtual and augmented reality experiences. You can develop interactive VR/AR applications and experiments that run in web browsers, making it accessible to a wider audience without requiring specialized hardware or installations.
  5. Physical Computing and Internet of Things (IoT): p5.js can be combined with hardware platforms such as Arduino or Raspberry Pi to interact with the physical world. You can create projects that involve sensors, actuators, and other IoT devices, enabling real-time interactions between the digital and physical realms.
  6. Machine Learning and Artificial Intelligence: p5.js has extensions and libraries that integrate with machine learning frameworks such as TensorFlow.js. This allows you to create projects that involve image recognition, natural language processing, neural networks, and other AI-powered interactions, opening up possibilities for interactive and intelligent applications.
  7. Audiovisual Performances and Installations: p5.js can be used to create immersive audiovisual experiences for live performances and installations. By combining visuals, sound, interactivity, and motion, you can create captivating and interactive installations, audiovisual performances, and interactive art pieces.
  8. Mobile App Development: With frameworks like p5.js for Processing, you can create mobile apps for iOS and Android using p5.js syntax. This allows you to leverage the capabilities of p5.js to build interactive and visually appealing mobile applications.

These are just a few examples of the advanced uses of p5.js. The library’s flexibility, extensive documentation, and active community support provide a solid foundation for pushing the boundaries of creative coding and interactive web development. By exploring additional p5.js libraries, extensions, and examples, you can unlock even more possibilities and create unique and innovative projects.

More Help

To get more help and assistance with p5.js, you can explore the following resources:

  1. p5.js Website: The official p5.js website (https://p5js.org/) is a valuable resource for getting started with p5.js. It provides documentation, tutorials, examples, and a reference guide that cover the various features and capabilities of the library.
  2. p5.js Forum: The p5.js forum (https://discourse.p5js.org/) is a community-driven platform where you can ask questions, seek help, and engage in discussions with other p5.js users. It’s a great place to find answers, share your projects, and connect with fellow creators.
  3. p5.js GitHub Repository: The p5.js GitHub repository (https://github.com/processing/p5.js) hosts the source code of p5.js. You can browse the repository to explore the codebase, file issues, and contribute to the development of the library.
  4. YouTube Tutorials: Many creators and educators share p5.js tutorials and demonstrations on YouTube. Searching for “p5.js tutorials” will give you access to a wide range of video tutorials that can help you learn different aspects of p5.js and inspire your projects.
  5. Online Communities: Apart from the official p5.js resources, there are online communities and platforms where you can connect with other p5.js enthusiasts. Websites like CodePen (https://codepen.io/) and Glitch (https://glitch.com/) feature a large collection of p5.js projects and allow you to remix and explore code shared by the community.
  6. Books and Learning Platforms: There are several books and online learning platforms that offer in-depth tutorials and courses on p5.js. Some popular resources include “Getting Started with p5.js” by Lauren McCarthy, “Make: Getting Started with p5.js” by Ben Fry, and online learning platforms like Khan Academy (https://www.khanacademy.org/computing/computer-programming/programming) and Coding Train (https://www.youtube.com/user/shiffman/playlists).

Remember, experimenting, practicing, and exploring different examples are great ways to learn and become more proficient with p5.js. Don’t hesitate to ask questions, seek feedback, and share your work with the community. The p5.js community is welcoming and supportive, and there are plenty of resources available to help you along your creative coding journey.

1 thought on “p5.js

  1. Pingback: Code for Solo Play – 334 Digital

Comments are closed.