Open In App

p5.js model() Function

Last Updated : 11 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The model() function is used to render a 3D model to the screen. The model to be rendered has to be loaded first using the loadModel() function.

Syntax:

model( model )

Parameters: This function accepts one parameter as mentioned above and described below.

  • model: It is the p5.Geometry object that specifies the model that has to be rendered to the screen.

The program below illustrate the model() function in p5.js:

Example:




let ballObj, cubeObj, coneObj;
let currentObj;
let newFont;
  
// Load all the models in preload()
function preload() {
  newFont = loadFont("fonts/Montserrat.otf");
  ballObj = loadModel("models/ball.obj", true);
  cubeObj = loadModel("models/cube.obj", true);
  coneObj = loadModel("models/cone.obj", true);
  currentObj = ballObj;
}
  
function setup() {
  createCanvas(400, 300, WEBGL);
  
  textFont(newFont, 14);
  
  modelSelector = createSelect();
  modelSelector.position(30, 40);
  modelSelector.option("ball");
  modelSelector.option("cube");
  modelSelector.option("cone");
  modelSelector.changed(modelChanged);
}
  
// Function to change the model depending
// on the selected dropdown 
function modelChanged() {
  let selected = modelSelector.value();
  console.log(selected);
  switch (selected) {
    case "ball":
      currentObj = ballObj;
      break;
    case "cube":
      currentObj = cubeObj;
      break;
    case "cone":
      currentObj = coneObj;
      break;
    default:
      break;
  }
}
  
function draw() {
  background("green");
  text("Use the dropdown to select the model to display", -185, -125);
  scale(0.75);
  lights();
  rotateX(frameCount * 0.05);
  rotateY(frameCount * 0.05);
  noStroke();
  
  // Load the given model
  model(currentObj);
}


Output:

model-selector

Reference: https://p5js.org/reference/#/p5/model



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads