Open In App

p5.js | drop() Function

Last Updated : 20 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The drop() function is an inbuilt function which is used to register a callback function that gets called every time when a file has been dropped on the element after loading it. Every dropped file is loaded into memory and pass it as p5.File object to the callback function. When multiple files drop at the same time then it will display multiple calls to the callback function.

This function requires p5.dom library. So add the following line in the head section of the index.html file.




<script language="javascript" 
    type="text/javascript" src="path/to/p5.dom.js">
</script>


Syntax:

drop( callback, fxn )

Parameters: This function accepts two parameters as mentioned above and described below:

  • callback: This parameter is used to hold the loaded file which is called for each file drop.
  • fxn: This parameter is used when callback function is triggered when files are dropped with the drop event.

Below examples illustrate the drop() function in p5.js:

Example 1:




function setup() {  
     
    // Create Canvas of given size 
     var cvs = createCanvas(400, 300);
      
    // Set the background color
    background('red');
    
    // Set the text position
    textAlign(CENTER);
      
    // Set the font size
    textSize(24);
      
    // Set the text color
    fill('white');
      
    // Display the text on the screen
    text('Drop file from device', width / 2, height / 2);
      
    // Function to drop the file
    cvs.drop(gotFile);
}
  
function gotFile(file) {
    
  // Set the background color
  background('green');
    
  // Display the text on the screen
  text('Received file name with extension:', width / 2, height / 2);
    
  // Drop file with given position
  text(file.name, width / 2, height / 2 + 50);
}


Output:

  • Before Drop a File:
    drop file function
  • After Drop a File:
    drop file

Example 2:




var img;
  
function setup() {  
     
    // Create Canvas of given size 
     var cvs = createCanvas(600, 400);
      
    // Set the background color
    background('red');
    
    // Set the text position
    textAlign(CENTER);
      
    // Set the font size
    textSize(24);
      
    // Set the text color
    fill('white');
      
    // Display the text on the screen
    text('Drop file from device', width / 2, height / 2);
      
    // Function to drop the file
    cvs.drop(gotFile);
}
  
function draw() {
  if (img) {
    image(img, 0, 0, width, height);
  }
}
  
function gotFile(file) {
  img = createImg(file.data).hide();
}


Output:

  • Before Drop a File:
    drop file
  • After Drop a File:
    drop file


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

Similar Reads