Upload multiple canvas images through javascript loop

前端 未结 4 1426
感情败类
感情败类 2021-01-28 17:36

I am trying to make an upload script which resizes multiple images client side before the saveimage.php handles them. The reason for this is because they will be upload

4条回答
  •  逝去的感伤
    2021-01-28 17:48

    I had kind of the same issue, but I got to manage that by first displaying all the images in a hidden "img" tag taking as a reference this post "HTML5 to display uploaded image untill next one is uploaded?" and after that I trigger a function with an additional button that uses the recent created images and draw all of them in an separated canvas that were also created at the same time that the images where uploading, the code will be like this

    the html:



    The script:

    document.getElementById('files').addEventListener('change', handleFileSelect,false);  
        document.getElementById('run').addEventListener('click', read);
    
        function handleFileSelect(evt) {
          var files = evt.target.files; // FileList object
    
          // Loop through the FileList and render image files as thumbnails.
          for (var i = 0, f; f = files[i]; i++) {
    
            // Only process image files.
            if (!f.type.match('image.*')) {
              continue;
            }
    
            var reader = new FileReader();
    
            // Closure to capture the file information.
            reader.onload = (function(theFile) {
              return function(e) { 
                // Render thumbnail.
                var span = document.createElement('span');
                span.innerHTML = [''].join('');
                document.getElementById('list').insertBefore(span, null);
                var span = document.createElement('span');
                span.innerHTML = [''].join('');
                document.getElementById('list2').insertBefore(span, null);                       
              };
            })(f);
            // Read in the image file as a data URL.
            reader.readAsDataURL(f);
          }
        } 
    
    function read() { 
        imgs = document.getElementsByName('forms'); 
        canvas = document.getElementsByTagName("canvas");
        for (var i = 0; i < imgs.length; ++i) { 
            ctx[i] = canvas[i].getContext("2d");
            ctx[i].clearRect(0, 0, canvas[i].width, canvas[i].height);
            preview.style.width = imgs[i].width + "px";
            preview.style.height = imgs[i].height + "px";
            canvas[i].width = imgs[i].width;
            canvas[i].height = imgs[i].height;                           
            ctx[i].drawImage(imgs[i], 0, 0, imgs[i].width, imgs[i].height);
            // do all you need with each new canvas canvas
        }
    }
    

提交回复
热议问题