3

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]);
 }; 
6
  • 10
    why would you want to upload the same file more than once? Reuse the uploaded file! Commented Jul 15, 2013 at 16:22
  • I just figured that's the most intuitive way for the user to insert duplicate images. Commented Jul 15, 2013 at 16:24
  • How would the user indicate, other than uploading the same image again, that they want two of one image on the canvas then? Commented Jul 15, 2013 at 16:47
  • There is no upload here... Commented Jul 15, 2013 at 16:48
  • 1
    well, how do you determine now it is the same image? Commented Jul 16, 2013 at 9:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.