Open In App

p5.js | drop() Function

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:



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:

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:


Article Tags :