How to create advanced 2D shapes in p5.js
The p5.js library makes it easy to bring graphics and visual elements to our creative coding projects with shapes. While its core functions allow us to draw basic shapes like circles, squares, and triangles, p5.js also offers the tools to build more complex and advanced forms.
Merging basic shapes
Let’s create advanced shapes by merging basic shapes, such as rectangles and ellipses. This requires us to be diligent about setting up and using the
Let’s look at an example of how this would work.
Example: Basic shapes
In this example, we’ll use a rectangle and an ellipse to create a "D" shape.
Code explanation
Lines 1–4: The
xandyvariables store the coordinates of the shapes. Thesizevariable stores the size of the shapes.Lines 7–33: The
setup()function sets up the application canvas and the background. We initializexandyto the center of the canvas, and set the rectangles and ellipses to be drawn from their center point. Then, we draw a rectangle and an ellipse using thex,y, andsizevariables.
Advanced shapes
Next, let’s look at how to create advanced polygonal shapes using the beginShape(), endShape(), and vertex() functions.
The beginShape() and endShape() functions
The beginShape() begins recording vertices for a shape, and the endShape() stops recording. Let’s look at the signatures for these functions:
beginShape([kind])
kindis an optional parameter. It’s eitherPOINTS,LINES,TRIANGLES,TRIANGLE_FANTRIANGLE_STRIP,QUADS,QUAD_STRIP, orTESS. It controls the "look" of the shape.
endShape([mode], [count])
modeis an optional parameter. We can useCLOSEto close the shape, i.e., connect the starting point to the ending point.countis also an optional parameter. It represents the number of times we want to draw/instance the shape.
The vertex() function
Shapes in p5.js are built by connecting a series of points called vertices. The vertex() function defines the coordinates of these points within the beginShape() and endShape() functions.
The signature of the vertex() function looks like this:
vertex(x, y, [z], [u], [v])
xis the "x" coordinate of the vertex.yis the "y" coordinate of the vertex.zis the "z" coordinate of the vertex. It defaults to 0 if not specified. (Optional)uis the vertex's texture "u" coordinate. (Optional)vis the vertex's texture "v" coordinate. (Optional)
In practice, we usually work with the x and y parameters to create 2D shapes.
Example: Advanced polygonal shapes
Let’s look at an example of creating advanced shapes using these functions. In this example, we can see the effect of the kind variable in showing "kinds" of the beginShape() and endShape() functions. Press the keys "0" to "7" to see the results. Press "c" to open and "v" to close the shape. Press "f" to fill and "g" to empty the shape. Feel free to play around with the code below!
Code explanation
Lines 1–7: The
kindvariable stores the type of shape to be drawn. ThekindStrvariable stores a text description of the shape type. TheisClosedvariable determines whether the shape will be closed or open. TheisFilledvariable determines whether the shape will have a filled color or an outline.Lines 10–14: The
setup()function sets up the application canvas and the background. ThecreateCanvas()function creates the drawing space with a width of500pixels and a height of500pixels. The background function sets the initial background color to gray. TheframeRate()function sets a target of drawing60frames per second.Lines 17–74: The
draw()function handles the continuous update process. The code responds to key presses, letting the user switch between shape types (like points, lines, triangles), toggle whether shapes are closed or open, and control whether the shapes have a fill color. Additionally, alabelfunction displays the current settings for clarity.Lines 76–97: The
drawShape()function creates a polygonal shape using predefined vertices.Lines 100–111: The utility function
label()displays labels. It sets the fill color to black, draws a centered rectangle above the bottom edge of the canvas, sets text alignment to center, sets the textfill()color to white, sets thetextSize()to16pixels, and displays the input stringlabat the center of the rectangle above the bottom edge.
Conclusion
The p5.js library allows us to create complex shapes with ease. There are also methods to create 3D shapes. You can look into the count parameter in the endShape() method for further exploration. Also, there are functions like bezierVertex(), curveVertex(), and quadraticVertex() to create even more complex shapes.
Unlock your potential: p5.js fundamentals series, all in one place!
To deepen your understanding of p5.js, explore our series of Answers below:
What is p5.js?
p5.js is an open-source JavaScript library for creative coding, designed for visualizations, games, and interactive art, with a beginner-friendly approach.How to color shapes in p5.js
Learn how to apply colors to shapes usingfill(),stroke(), and transparency to create stunning visual effects.How to use images in p5.js
Discover how to load, display, and manipulate images in p5.js to enhance dynamic and interactive sketches.How to use image filters in p5.js
Enhance your images with built-in filters like grayscale, blur, and threshold to achieve unique visual effects.How to create advanced 2D shapes in p5.js
Master the creation of complex 2D shapes using curves, vertices, and transformations for custom designs.How to add keyboard interaction in p5.js
Learn how to detect and respond to keyboard input to add interactivity to your sketches.How to use vectors in p5.js
Explore the power of vectors for motion, physics simulations, and dynamic interactions in creative coding.How to add mouse interaction in p5.js
Implement mouse-based interactions such as clicks, drags, and movement tracking to enhance user engagement.
Free Resources