Getting the error Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The image argument is a canvas element with a width or height of 0

I am trying to make a Delaunay triangulation sketch in p5. i have successfully made it to work with an image url. i want to allow the user to upload some images too, but when i am trying to do so, i get the following error:

p5.min.js:3 Uncaught DOMException: Failed to execute ‘drawImage’ on ‘CanvasRenderingContext2D’: The image argument is a canvas element with a width or height of 0.

my entire code would be very long so the relevant parts are:

let img;
let num_triangles = 5000;

function preload() {
  img = loadImage("https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg");
}

function setup() {
  input = createFileInput(handleFile);
  input.position(0, 0);

  noLoop()
}

function draw() {
  img.resize(img.width / 2.5, img.height / 2.5)
  createCanvas(img.width, img.height);
  background(255);
  pixelDensity(1)
  img.loadPixels();
  loadPixels()
  // the actual drawing here, but the error is reached before it so i dont think this code is needed
}

function handleFile(file) {
  print(file);
  if (file.type === 'image') {
    img = loadImage(file.data);
    console.log(img)
    draw()
  }
}

EDIT: just found out this works:

function handleFile(file) {
  print(file);
  if (file.type === 'image') {
    img = loadImage(file.data);
    console.log(img.width)
    setTimeout(() => {
      console.log(img.width)
      draw()
    }, 1000);
  }
}

the width is 1 at first, but after 1 second, it changes to the actual thing.

Hi,

I suppose it’s because your image isn’t loaded yet when you call draw(), so you should give a callback function to loadFile to run it after image is loaded (https://p5js.org/reference/#/p5/loadImage) :

loadImage('assets/laDefense.jpg', img => {
    image(img, 0, 0);
  });