Control order of image load events

Asked

Viewed 35 times

2

I need to upload some images by input file. So far so good.

However, I need these images uploaded in order. But when I put img.onload = Function() {} inside the for, the order of the variable i, is completely different, so the images created by the canvas, too, are.

As the images I am loading are very large, I need to compress them so that when I generate the PDF file I do not get a huge size. 14 photos are giving 62MB PDF.

Here’s a picture of how I need you to stay

And here’s how it looks, because the variable i is completely out of order

inserir a descrição da imagem aqui

Thank you very much.

var filesInput = $("#file");
filesInput.on("change", function(e) {

    $("#divImagesFrame").show();

    /* Manipulação das fotos */
    var files = e.target.files;
    var result = $("#divImagesFrame");
    var filesLength = this.files.length;

    var page = 1;
    var count = 6;

    $("#blur, #pageName").html($("#txtCliente").val());

    result.append("<div class='pageTitle'><div class='pageBox'>" + page + "</div><span>" + $("#txtCliente").val() + "<span class='localName'>" + $("#txtCampanha").val() + "</span></span></div>");

    for (let i = 0; i < this.files.length; i++) {

        qtdFotos++;
        let url = URL.createObjectURL(this.files[i]);
        let img = new Image();
        img.src = url;

        console.log("ID outside img.load: " + i);

        img.onload = function() {

            console.log("ID inside img.load: " + i);

            var busNumber = files[i].name.toString().split(".")[0];
            var dataFoto = files[i].lastModified;
            var d = new Date(dataFoto);
            d.toLocaleString();

            var canvas = document.createElement('canvas');
            canvas.width = 460;
            canvas.height = 360;
            ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

            var imageFile = canvas.toDataURL("image/JPEG", 1.0);

            /* In this result.append, if I put the image source = img.src the order of images stay ok, but the size is much larger */
            result.append("<div class='imageFrame' style='width:460px; border-radius:10px; height:360px; float:left; margin:14.01px 20px; box-shadow:1px 1px 3px 0.8px #999;'>" +
                "<div style='float:left;border-radius:10px 10px 0 0; background:linear-gradient(-90deg,#105e86,#125e86); display:block; width:450px; height:40px; font-weight:550; font-size:23px; line-height:40px; padding-left:10px; color:#FFF;'>" + busNumber + "<span style='font-size:18px; float:right; margin-right:20px;'>" + d.toLocaleDateString() + "</span></div>" +
                "<img width='460px' height='320px' style='border-radius:0 0 10px 10px; margin-bottom:5px;' src='" + imageFile + "'/></div>");

        }


    }

    sammiCreateBook();
});
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.