p5.js | storeItem() Function

The storeItem() function is used to store a given value under a key name in the local storage of the browser. The local storage persists between browsing sessions and can store values even after reloading the page.

It can be used to save non-sensitive information, such as user preferences. Sensitive data like personal information should not be stored as this storage is easily accessible.

Syntax:



storeItem(key, value)

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

  • key: This is a string which denotes the key under which the value would be stored.
  • value: This is any value that can be stored under the key. It can be a String, Number, Boolean, Object, p5.Color or a p5.Vector.

Below example illustrates the storeItem() function in p5.js:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

function setup() {
  createCanvas(400, 300);
  fill("green");
  text("Click anywhere to draw a circle", 10, 20);
  text("The last circle would be redrawn when page is refreshed", 10, 40);
  
  // get the coordinates 
  // from localStorage
  oldX = getItem('xpos');
  oldY = getItem('ypos');
  
  // check if the values are
  // actually present (not null)
  if (oldX != null && oldY != null)
    circle(oldX, oldY, 100);
    
}
  
function mouseClicked() {
  clear();
  fill("green");
  text("Click anywhere to draw a circle", 10, 20);
  text("The last circle would be redrawn when page is refreshed", 10, 40);
  
  posX = mouseX;
  posY = mouseY;
  circle(posX, posY, 100);
  
  // set the coordinates
  // to localStorage
  storeItem('xpos', posX);
  storeItem('ypos', posY);
}

chevron_right


Output:

  • Local storage of the browser
    local-storage
  • 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/storeItem



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.