简体   繁体   English

上传相同的图像文件两次 - Javascript

[英]Upload the same image file twice - Javascript

I have an image uploader in my drawing application that I've written in Javascript. 我在我的绘图应用程序中有一个用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]);
 }; 

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. 我确实倾向于同意Rene Pot再次使用相同的图像(重复按钮),但您仍然无法阻止用户再次插入/加载相同的图像。 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). 我前一段时间遇到过这个问题并使用这段代码检查图像是否已经缓存(如果缓存,则没有加载,因此onload也不会触发)。

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. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM