Updating the code of a running p5js sketch

Actually, you can collect and execute code interactively, but as you and @davepagurek have noted, that could be dangerous.

The following uses prompt() to accumulate code that can be typed or pasted in:

let codeToExecute = "";
function setup() {
  createCanvas(200, 200);
}

function draw() {
  // accumulate code to execute during each call to draw()
  let newCode = prompt("Additional code to accumulate (Cancel to stop draw() cycling): ");
  if (newCode === "" || newCode == null) {
    noLoop();
  } else {
    codeToExecute += newCode;
    eval(codeToExecute);
  }
}

This code was pasted in at the prompt to produce the image that follows below it:

rectMode(CENTER);
ellipse(width / 2, height / 2, width - 10, height - 50);
rect(width / 2, height / 2, width - 40, height - 90);

eval

Whether this is dangerous depends upon how much the source of the code can be trusted. When a user is free to enter code to be executed, it’s time to get nervous. :face_with_open_eyes_and_hand_over_mouth:

2 Likes