'moving a sketch from draw to setup

Im playing around with the prime spiral code from Dan Shiffman: https://www.youtube.com/watch?v=a35KWEjRvc0&t=716s&ab_channel=TheCodingTrain

I need to use this code as a background to another sketch, but due to the moving nature of the spiral its impossible that the spiral will not draw ontop of the other sketch, even with p5.layers.

I am therefore searching for a way to refactor this code into something that draw all the figures at once so use it as a background. My idea is to create some kind of for loop in setup, but i am afraid its to big of nut to crack for me.

let x, y;
let step = 1;
let stepSize = 20;
let numSteps = 1;
let state = 0;
let turnCounter = 1;
let totalSteps;
let offset = 0;

function isPrime(value) {
  if (value == 1) return false;
  for (let i = 2; i <= sqrt(value); i++) {
    if (value % i == 0) {
      return false;
    }
  }
  return true;
}

function setup() {
  createCanvas(500, 500);

  const cols = width / stepSize;
  const rows = height / stepSize;
  totalSteps = cols * rows;

  x = width / 2;
  y = height / 2;
  background(0);
}

function draw() {

  primeSpiral(20, 1)
  primeSpiral(30, 200)
  
  incrementStep();
  
  noStroke();
}

function incrementStep()
{
  switch (state) {
    case 0:
      x += stepSize;
      break;
    case 1:
      y -= stepSize;
      break;
    case 2:
      x -= stepSize;
      break;
    case 3:
      y += stepSize;
      break;
  }

  if (step % numSteps == 0) {
    state = (state + 1) % 4;
    turnCounter++;
    if (turnCounter % 2 == 0) {
      numSteps++;
    }
  }
  step++;

  if (step > totalSteps) {
    noLoop();
  }
}

function primeSpiral(offset, color){
  if (!isPrime(step+offset)) {
    //might put something here

  } else {
    let r = stepSize * 0.5;
    fill(color, 99, 164);
    push();
    translate(x, y);
    rotate(-PI / 4);
    triangle(-r, +r, 0, -r, +r, +r);
    pop();
  }


}


Solution 1:[1]

You can move the code from draw() to the loop in setup(), here is example:

...

function setup() {
  createCanvas(500, 500);

  const cols = width / stepSize;
  const rows = height / stepSize;
  totalSteps = cols * rows;

  x = width / 2;
  y = height / 2;
  background(0);
    
  for (let i = 0; i<100; i++) { // 100 is the number of processed frames, you can change it as you need
    primeSpiral(20, 1)
    primeSpiral(30, 200)
    incrementStep();
    noStroke();
  }
}

function draw() {    // now draw is empty and you can place new code here
}
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hayabuzo