getImageData returns 以前上传图片的值不是当前图片

getImageData returns values from previous uploaded picture not current

当下面的代码 returns 值来自以前上传的图片而不是当前图片时,有人能告诉我哪里出错了吗?

    var imageLoader = document.getElementById('imageLoader');
    imageLoader.addEventListener('change', handleImage, false);
    var canvas = document.getElementById('imageCanvas');
    var ctx = canvas.getContext('2d');


    function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
    var img = new Image();
    img.onload = function(){
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img,0,0);
    }
    img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);     


    var imageWidth = canvas.width;
    var imageHeight = canvas.height;


    var imageData = ctx.getImageData(0,0,imageWidth,imageHeight);
    var data = imageData.data;

    console.log("imageWidth=" +imageWidth); 

图片通过下方输入上传:

  <canvas id="imageCanvas"></canvas>
  <br>
  <input type='file' id="imageLoader" name="imageLoader"/>
  <br>

有什么想法吗?

load FileReader<img> 的事件都是异步的。地点

var imageWidth = canvas.width;
var imageHeight = canvas.height;

var imageData = ctx.getImageData(0,0,imageWidth,imageHeight);
var data = imageData.data;

console.log("imageWidth=" +imageWidth); 

<img> load 事件处理程序中。

您还可以将 <input type="file"> 元素的 .value 设置为 "" 以从元素的 .files 属性.