Upload the same image file twice - Javascript

I have an image upload application in my drawing application that I wrote in Javascript. I want to allow the user to place several identical images on the canvas. However, when I try to load an image that is already on the canvas, nothing happens and the breakpoint in my event handler for the loader never hits. What is happening and how can I fix it? Thanks!

Here is 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]); }; 
+4
source share
1 answer

I usually agree with Rene Pot to use the same image again (duplicate button), but you still cannot prevent the user from pasting / loading the same image again. I ran into a problem a while ago and used this bit of code to verify that the image is already cached (if cached, there is no download, so it won’t work).

 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 this helps.

0
source

Source: https://habr.com/ru/post/1491478/


All Articles