Example of Preload with await using a Files class

We can easily add the other functions starting with “load”.

Sketch here

Code :

function setup() {
  createCanvas(500, 400);
  textSize(30);
  textAlign(CENTER);
  imageMode(CENTER);
  
  Files.loadImage("chat01.jpg");
  Files.loadImage("chat02.jpg");
  Files.loadImage("chat03.jpg");
  Files.loadImage("chat04.jpg");
  Files.loadImage("chat05.jpg");
  Files.loadImage("chat06.jpg");
  Files.loadImage("chat07.jpg");
}

function draw() {
  background(200);
  translate(width/2, height/2);
  
  if (Files.preload) Files.wait();
  else {
    Files.get("chat06.jpg").resize(0, height);
    image(Files.get("chat06.jpg"), 0, 0);
  }
}

class Files {
  static files=new Map(); // <string,object>
  static filesToLoad=0;
  static filesLoaded=0;
  static filename="";
  static preload=true;

  static async loadImage(filename, path="") {
    Files.filesToLoad+=1;
    Files.files.set(filename, await loadImage("data/"+path+filename));
    Files.filesLoaded+=1;
    Files.filename=filename;
  }

  static get(filename) {
    return Files.files.get(filename);
  }

  static wait() {
    push();
    stroke(0);
    rect(-200, 0, 400, 50);
    noStroke();
    fill(0, 0, 255);
    rect(-200, 0, map(Files.filesLoaded/Files.filesToLoad*100, 0, 100, 0, 400), 50);
    fill(0);
    textSize(30);
    text(Files.filename, 0, 100);
    pop();
    if (Files.filesLoaded==Files.filesToLoad) {
      Files.preload=false;
      Files.filename="";
    }
  }
}

2 Likes