0

I'm loading a picture from local storage and putting it to a canvas on top of another picture.

function imageProcessing(camera, canvas, canvasContext, selectedOverlayImage, stream, selectedImage) {
  let loaded = false;
  let overlayImg = new Image();

  if (camera) {
    canvasContext.drawImage(stream, 0, 0, canvas.width, canvas.height);
  } else {
    canvasContext.drawImage(selectedImage, 0, 0, canvas.width, canvas.height);
  }

  function createImg() {
    if (loaded) { return ; } else { loaded = true; }
    canvasContext.drawImage(overlayImg, 0, 0, canvas.width, canvas.height);
    let imageData = canvas.toDataURL('image/png');
    //Call php to create picture in database
    fetch("http://localhost:8000/picture-editing.php", {
      method: "POST",
      headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
          body: `imageData=${imageData}`
    }).catch(err => console.error(err));
  }

  overlayImg.addEventListener('load', createImg);
  overlayImg.src = `overlayImages/${selectedOverlayImage}.png`;
  if (overlayImg.complete) { createImg(); } //Certain images are already loaded but still need to go through createImg function
}

Basically after loading the image here: overlayImg.addEventListener('load', createImg);, the following function should run function createImg(). But it sometimes does not call createImg(), the larger the image the least chance it will call that function. A couple of months ago I didn't have this problem.

I am using a mac, I tried on Chrome, safari, from a docker container and outside a docker container. I tried everything I could find on the internet without success... Thank you for your help!

artainmo
  • 3
  • 3
  • I don't know enough to really give enough of an answer, but I've had similar issues in Typescript and sometimes JavaScript where it ended up being a race condition of some sort. This seems to be what the code here https://stackoverflow.com/questions/280049/how-to-create-a-javascript-callback-for-knowing-when-an-image-is-loaded tries to fix – zack Aug 26 '22 at 20:39
  • Try adding `error` event listener and check if you are getting any errors – Konrad Aug 26 '22 at 20:53
  • The error event does not work neither... – artainmo Aug 26 '22 at 21:51

0 Answers0