Why is toDataURL() returning blank image? (with p5 video)

I'm using p5 to display a video with the webcam and send a picture of it when the user clicks a button (along with lat & lon cords). For some reason though, toDataURL() always returns a blank image. Here's what I have:

function setup() {            
    noCanvas();
    const video = createCapture(VIDEO);
    video.size(320,240);
    video.loadPixels();

    submit.addEventListener('click', async event => {
        position().then(({lat, lon}) => {
            const image = video.canvas.toDataURL();
            data(lat, lon, image);
        })
    })
}

submit is the button data() is the function I'm using to generate a json and send it to the server

I tried to move the .addEventListener() outside of setup() but it did not work

1 Answers

The issue might be related to the timing of when the toDataURL() method is being called. In this case, you are trying to capture the image when the submit button is clicked. However, it seems like you are not waiting for the video to fully load before trying to convert it to a data URL.

To address this, you can ensure that you are waiting for the video element to be fully loaded before attempting to convert it to a data URL. One way to do this is by using the loadeddata event listener on the video element. This event is fired when the video metadata has been loaded.

Here's an updated version of your code that waits for the video to be loaded before attempting to convert it to a data URL:

let video;

function setup() {
  createCanvas(320, 240);

  video = createCapture(VIDEO);
  video.size(320, 240);

  video.elt.addEventListener('loadeddata', () => {
    submit.addEventListener('click', async event => {
      getPosition().then(({lat, lon}) => {
        const image = video.canvas.toDataURL();
        sendData(lat, lon, image);
      })
    });
  });
}

function getPosition() {
  // Your position retrieval logic here
}

function sendData(lat, lon, image) {
  // Your data sending logic here
}

In this version, the loadeddata event listener ensures that the submit button click event listener is only added after the video has loaded its metadata. This should help in ensuring that the image data is captured correctly.