Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptp5.js loadImage() Function

p5.js loadImage() Function

The loadImage() function is used to load an image from the given path and create a p5.Image object with the image.

It is advised to load an image in the preload() function as the loaded image may not be available for use immediately. The image is preferably loaded from a relative path as some browsers may prevent loading from other remote locations due to the browser’s security features.

Syntax:

loadImage(path, successCallback, failureCallback)

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

  • path: This is the path from where the image is to be loaded.
  • successCallback: This is a function which is called if the image successfully loads and it is an optional parameter.
  • failureCallback: This is a function which is called if the image does not load due to any error and it is an optional parameter.

Below examples illustrates the loadImage() function in p5.js:

Example 1: This example shows the loading of image in preload().




let img;
  
function preload() {
  img = loadImage('sample-image.png');
}
  
function setup() {
  createCanvas(300, 200);
  
  text("The image would be loaded below:", 20, 20);
  image(img, 20, 40, 100, 100);
}


Output:

load-image

Example 2: This example shows loading an image from a URL and both callbacks that may take place.




let img;
let url = 
  
function setup() {
  createCanvas(400, 200);
  
  textSize(18)
  text("The image would be loaded below:", 20, 20);
  
  loadImage(url, img => {
    image(img, 20, 40, 100, 100);
  },
    (event) => {
      fill("red")
      text("Error: The image could not be loaded.", 20, 40);
      console.log(event);
    }
  );
}


Output:

  • Image successfully loads
    load-image-success
  • Image does not load
    not-loaded-error

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments