Pergunta

I have an image uploader in my drawing application that I've written in Javascript. I want to allow the user to place multiple of the same image on the canvas. However, when I try to upload an image that's already on the canvas, nothing happens and a breakpoint in my event handler for the uploader never gets hit. What's going on and how can I fix it? Thanks!

Here's the code for my image handler:

function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
  var img = new Image();
  img.onload = function() {
    img.className = 'drag';
    img.style.left = 0;
    img.style.top = 0;
    context.drawImage(img, parseInt(img.style.left, 10) , parseInt(img.style.top, 10));
    images.push(img);
  }
  img.src = event.target.result;
 }
 reader.readAsDataURL(e.target.files[0]);
 }; 
Foi útil?

Solução

I do tend to agree with Rene Pot to use the same image again (duplicate button), but you still can't prevent the user from inserting/loading the same image again. I've encountered the problem a while ago and used this bit of code to check if the image is already cached (if cached, there is no load, hence the onload won't fire either).

var img = new Image();
img.src = event.target.result;

var insertImage = function() {
    img.className = 'drag';
    img.style.left = 0;
    img.style.top = 0;
    context.drawImage(img, parseInt(img.style.left, 10) , parseInt(img.style.top, 10));
    images.push(img);
  }

if(img.complete){
   img.onload = insertImage;
} else {
   insertImage();
}

Hope that helps.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top