There's an artist in all of us, and with the help of the p5.js library, you can awaken that artist and create stunning visuals right in your browser! Let's dive into the world of shapes and colors using p5.js.
Setting Up p5.js
First things first - we need to get p5.js up and running. To begin, create an HTML file and include the p5.js library using a script tag. You can either download p5.js from the official website or use a CDN (Content Delivery Network) like this:
Now, create a
sketch.js file in the same directory as your HTML file. This file is where we'll write our p5.js code.
Before we start drawing shapes, we need a canvas to draw on. p5.js makes this easy with the
createCanvas() function. We also need to define two essential functions:
setup() function is called once when the program starts, and the
draw() function is called repeatedly, creating an animation loop.
Now that we have our canvas, let's start drawing some shapes!
p5.js offers a wide range of primitives to draw shapes. In this guide, we'll cover rectangles, circles, and triangles.
To draw a rectangle, use the
rect() function, which requires four parameters: the x and y coordinates of the top-left corner, and the rectangle's width and height.
Drawing circles is just as straightforward with the
circle() function. You'll need three parameters: the x and y coordinates of the circle's center and the diameter.
Triangles are a bit more complex, as we need to specify the x and y coordinates of each vertex. The
triangle() function takes six parameters: x1, y1, x2, y2, x3, and y3.
Colors and Styles
Our shapes would look more vibrant with some colors and styles! p5.js allows you to customize the stroke (border color), fill, and stroke weight (border thickness).
And there you have it - a guide to creating art with shapes using the p5.js library. It's just the tip of the iceberg, though, so be sure to explore the p5.js reference for more shape functions, colors, and styles. Happy coding and drawing!
What are the basic shapes I can draw using p5.js?
With p5.js, you can draw various shapes like:
- Custom shapes
How can I draw a circle using p5.js?
To draw a circle in p5.js, use the
circle() function which takes three arguments:
circle(x, y, d) where
y are the coordinates of the circle's center, and
d is the diameter. For example:
How can I draw a rectangle or a square in p5.js?
To draw a rectangle, use the
rect() function which takes four arguments:
rect(x, y, w, h) where
y are the coordinates of the rectangle's top-left corner, and
h are its width and height, respectively. For example:
To draw a square, you can use the same
rect() function and set the width and height to be equal. For example:
How can I draw a custom shape using p5.js?
You can create custom shapes using the
endShape() functions, combined with the
vertex() function to define the shape's points. For example:
This code will create a custom pentagon shape.