Skip to content Skip to sidebar Skip to footer

Javascript Image Uploading Issue

I have this issue with a script that I was developing, to upload images on a canvas and with the cursor make it pass like a carousel VM20:158 Uncaught TypeError: Failed to execute

Solution 1:

reader.onload = function (e) {
    var img = document.createElement("IMG");

    img.src = e.target.result;

  imagenes.push(img.src);
  image_load="si"                       
}

You're creating a race condition here, and also pushing the src string to the array instead of the image. Before an image can be drawn to a canvas it has to be loaded, and you're not listening to the load event. The outcome is that sometimes the images have had enough time to load, and sometimes they did not, causing the error. It can work the second time because your browser is probably caching the images and they load faster. You can solve it like this:

reader.onload = function (e) {
  var img = document.createElement("IMG");
  img.onload = () => {
    imagenes.push(img);
    image_load="si" 
  }
  img.src = e.target.result;                    
}

EDIT: Now I see that you're creating another Image instance from the src later in the code, but the same problem happens there as well - you need to listen to the load event before you can draw it on a canvas.

Post a Comment for "Javascript Image Uploading Issue"