2015-07-01 155 views
1

我真的很基本的JS,但我需要完成一个任务是关于改变图片的选定部分的颜色。这已经很好地完成了我的一页html + js示例,现在我需要更改Rails应用程序以使用它。JS FileReader没有正确读取文件

我的主要问题是,在Rails应用程序中有一个已经放在页面上的图像(有很多图像,单独编辑),我无法让FileReader从它读取。

它会抛出中间'if'的情况 - '这个浏览器似乎不是......'这种情况到底意味着什么?我在这里找到了一个解释:Link但我不明白。我可以将一张给定的图片加载到画布上,但它仍然给我留言。哦,imgfile'stype是未定义的。为什么?...

下面的代码并不代表我的整个代码。

function loadImage() { 
      var input, file, fr, img, x; 

      if (typeof window.FileReader !== 'function') { 
       write("The file API isn't supported on this browser yet."); 
       return; 
      } 

      input = document.getElementById('imgfile'); 
      if (!input) { 
       write("Um, couldn't find the imgfile element."); 
      } 
      else if (!input.files) { 
       write("This browser doesn't seem to support the `files` property of file inputs."); 
       x = document.getElementById('imgfile').type; 
       write(x); 
      } 
      else if (!input.files[0]) { 
       write("Please select a file before clicking 'Load'"); 
      } 
      else { 
       file = input.files[0]; 
       fr = new FileReader(); 
       fr.onload = createImage; 
       fr.readAsDataURL(file); 
      } 
我编辑过这篇文章,因为它是基于错误的假设。

回答

0

FileReader应该从文件系统读取文件。 你下一步要做:

var img = new Image(); 
var canvas = document.createElement("canvas"); 
var ctx = canvas.getContext('2d'); 
img.onload = function(){ 
    ctx.drawImage(this, 0, 0); 
    ctx.toDataURL(); // <--- Here is your source of an image. 
}; 
img.src = document.getElementById('imgfile').src; 

不知道,为什么你需要阅读该网址您已有的图片。

+0

感谢您的回应,但它竟然是另一个问题。 – SzczesliwyCzlowiek

0

我回答自己,因为我找到了问题的根源 - 的FileReader可以由用户上传的文件只经营...