Open In App

How to create 3D Geometries in webGL and p5.js ?

Last Updated : 16 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to draw 3D geometry (containing length, width, and height) in p5.js. The default rendering in p5.js is used for 2D images, and for the 3D images, we use WEBGL which enables 3D render by introducing the Z dimension to the geometry.

Syntax:

createCanvas( windowWidth, windowHeight, WEBGL )

Example 1: In this example, we will use webGL and p5.js to create a 3D geometry and rotate it in all directions.

Javascript




// Create a canvas of given size
let angle = 0;
 
function setup() {
    createCanvas(600, 600, WEBGL);
}
 
// Create a draw function
function draw() {
    background(175);
    ambientLight(255);
    push();
 
    // Rotate the box in all dimensions
    translate(mouseX - width / 2,
            mouseY - width / 2);
             
    rotateX(angle);
    rotateZ(angle * 0.03);
    rotateY(angle * 0.06);
    noStroke();
    normalMaterial();
 
    // Create box of given size
    box(150, 150, 150);
    push();
    angle += .06
}


Output: 

Example 2: In this example, we will use webGL and p5.js to create a 3D geometry using image as side of geometry and rotate it in all directions. 

Javascript




// Create a canvas of given size
let angle = 0;
 
// Load the image in the
// preload function
function preload() {
    img = loadImage('gfg.jpg');
}
 
function setup() {
    createCanvas(600, 600, WEBGL);
}
 
// Create draw function
function draw() {
    background(175);
    ambientLight(255);
    push();
 
    // Rotate the box in all dimensions
    translate(10, 10, 10);
    rotateX(angle);
    rotateZ(angle * 0.03);
    rotateY(angle * 0.06);
    noStroke();
    normalMaterial();
 
    // Draw the texture
    texture(img);
 
    // Create box of given size
    box(150, 150, 150);
    push();
    angle += .06
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads