Overview
- p5.js is a JavaScript library that starts processing to make coding accessible for artists, designers, and beginners for today’s web.
- p5.js is a full set of drawing object functionality. However, you’re not limited to your drawing canvas, for this, p5.js has an add-on library that makes it easy to interact with other HTML5 objects.
- p5.js programs generally run in any browser. JavaScript interpreters are open-source and freely available and anyone can use it for free.
Get Started
- There are mainly two functions we will use in program.
- setup( ) and draw ( ), they are basically already in sketch.js file.
- The setup() block runs for creating a program that does not need a loop running code repeatedly. The draw() block runs repeatedly, and is used for animation or create the Shape, Objects, Drawing, etc…
Benefits
- P5.js is a full conversing Processing into javascript code and all the functions will be translated, and you’ll be writing in JavaScript.
- You write javascript code directly, and it performs code like any other javascript file you include on your website.
- P5 can be extended with add-on libraries.
Example
Step:1
- Draw triangle is a plane created by connecting three points (X,Y,Z).
- First Point Specify Two Arguments (x1,y1), Second Point Specify Two Arguments (x2,y2), Third Point Specify Two Arguments (x3,y3).
- Another Point (tx, ty) is the translation point that translates the object.
Syntax: triangle(x1, y1, x2, y2, x3, y3);
triangle.js
// Define Attribute class Triangle{ constructor(x1_, y1_, x2_, y2_, x3_, y3_, clr_, tx_, ty_, rot_){ this.x1 = x1_; this.y1 = y1_; this.x2 = x2_; this.y2 = y2_; this.x3 = x3_; this.y3 = y3_; this.clr = clr_; this.tx = tx_; this.ty = ty_; this.rot = rot_; } // Display Triangle display(){ push(); translate(this.tx, this.ty); fill(this.clr); rotate(this.rot); triangle(this.x1, this.y1, this.x2, this.y2, this.x3, this.y3); pop(); } }
index.html
// link triangle.js file in html code var mycolor; var t = []; function setup() { createCanvas(windowWidth, windowHeight); background(234, 226, 228); let clr = color('rgba(20, 159, 132, 255)'); t[0] = new Triangle(-50,40,50,40,0,-40,clr,210,120, 0); clr = color(39, 184, 153); t[1] = new Triangle(-50,40,50,40,0,-40,clr,210,210, 180); } function draw() { noStroke(); angleMode(DEGREES); translate (width / 3, height / 3); for(let i = 0; i < 2; i++){ t[i].display(); } }
Step:2
- Display new object with triangle shape by using class, variable, function.
Step:3
- Add animation effect by using mousePressed(), mouseDragged, mouseReleased() functions.
Video:
Demo Link: Click here
Conclusion
I hope this blog might help you to understand the few functions of p5.js. We would dig into other functions & bring light on it in later blogs. I would like to thank Sudev Kiyada for being so supportive to complete this blog.