Dawood Abbas
Dawood Abbas

Reputation: 83

How to merge multiple uploaded images by using Multi File Upload control?

I am trying to merge multiple images while retrieving the images from desk. It was taken from "How to create an image generator for combining multiple images?". It's working fine if single image is uploaded, but not working in case of multiple images.

This is my HTML code

<input id="file-input" type="file" name="images[]" multiple maxlength="5" ngf-select="UploadFiles($files)" accept=".png,.jpg,.jpeg,.gif" />
<canvas id="canvas"></canvas>

This is javascript code

    var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
    
        var lastImage;
        var lastHeight = 0;
        var lastWidth = 0;
        var imagesLoaded = 0;
    
        function max(a, b) {
            if (a > b)
                return a;
            return b;
        }
    
        function addToCanvas(img) {
            canvas.height = max(lastHeight, img.width);
            canvas.width = lastWidth + img.height;
    
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            if (lastImage) {
                ctx.drawImage(lastImage, 0, canvas.height - lastImage.height);
            }
    
            ctx.rotate(270 * Math.PI / 180); // rotate the canvas to the specified degrees
            ctx.drawImage(img, -canvas.height, lastWidth);
    
            lastImage = new Image();
            lastImage.src = canvas.toDataURL();
            lastWidth += img.height;
            lastHeight = canvas.height;
            imagesLoaded += 1;
        }
    
     $scope.UploadFiles = function (files) {
            $scope.SelectedFiles = files;
            cnt = files.length;
    
            console.log($scope.SelectedFiles);
    
            for (i = 0; i < $scope.SelectedFiles.length; i++) {
                console.log(files[i]);
                var reader = new FileReader();
    
                reader.onload = function (event) {
                    var img = new Image();
    
                    img.onload = function () {
                        addToCanvas(img);
                    }
    
                    img.src = reader.result;
                }
    
    
                reader.readAsDataURL(files[i]);
            }
        };

When I select images from the folder, the console's debugger stops at img.onload event, where I am trying to do action in loop.

Upvotes: 4

Views: 404

Answers (1)

Dawood Abbas
Dawood Abbas

Reputation: 83

For loop iteration not working for imageload functions..

files.map((file) => {
 var reader = new FileReader();
 reader.onload = (event) => {
 var img = new Image();
 img.onload = () => 
{
 addToCanvas(img);
}
img.src = reader.result;
 }
 reader.readAsDataURL(file);
 }
)

Upvotes: 4

Related Questions