P5.js Undo Tool

I hope everyone is doing well.

I’m trying to create an undo tool using P5.js.
I’m using a constructor function to make the tool.
What should I add to this function below? I want the undo button to work shapes.

Thank you


Pretend you are the undo button. When you get clicked, your job is to remove the last change made.

How are you going to know what the last change was?!? You will need some way to remember what the last shape added was, right? So you will need a data structure that tracks every shape that was added (and the shapes properties, probably), in order.

Using such a structure might also be useful for drawing the shapes.

Then, when you need to undo the last shape, you simply don’t draw the last one!

I wrote this button, but I can’t get it to work.


        let previousState;

	let stateIndex = 0;

	this.setup = function() {
	// createCanvas(400, 400);

	this.keyPressed = function(e) {
	// check if the event parameter (e) has Z (keycode 90) and ctrl or cmnd
	if (e.keyCode == 90 && (e.ctrlKey || e.metaKey)) {

	function undoToPreviousState() {
	// if previousState doesn't exist ie is null
	// return without doing anything
	if (!previousState) {
	// else draw the background (in this case white)
	// and draw the previous state
	image(previousState, 0, 0);
	// then set previous state to null
	previousState = null;

	this.mousePressed = function() {
	// the moment input is detect save the state

	function saveState() {
	// save state by taking image of background
	// for more info look at reference for get
	previousState = get();

Check this video below