用于多张图片上传的html5画布,不上传所有图片

时间:2013-08-22 21:33:05

标签: javascript jquery html html5 filereader

我正在尝试通过客户端的html5 filereader api调整多个图像的大小。它适用于单个图像,但对于多个图像,它通常只上传一个图像并留下其余的,我无法得到问题所在。这是我的代码

function handleFileSelect(evt) {


        var filesToUpload =  evt.target.files;

         for (var i = 0, f; f = filesToUpload[i]; i++) {



            var img = new Image();
            var reader = new FileReader();
            reader.readAsDataURL(f);
            reader.onload = function(e) {img.src = e.target.result; 
            };


            img.onload = function (){    // also tried reader.onloaded here

            canvas = document.createElement('canvas');
            var ctx = canvas.getContext("2d"); 
            ctx.drawImage(img, 0, 0);



            var MAX_WIDTH = 300;    // 2048
            var MAX_HEIGHT = 150;   // 1600
            var width = img.width;
            var height = img.height;



            if (width > height) {
              if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
              }
            } else {
              if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
              }
            }


            canvas.width = width;
            canvas.height = height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);


            var dataurl = canvas.toDataURL("image/jpeg");



            var newImgs = new Image();
            newImgs.src = dataurl;

            document.body.appendChild(newImgs);


        }    

    }

0 个答案:

没有答案