Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Execute function on onloadend event

I’m trying to execute functions after an onloadend event in order to append the uploaded image to a canvas and do some post procesing.

let fileInput = document.getElementById('fileinput');
    fileInput.addEventListener('change', function(ev) {
    if(ev.target.files) {
        let file = ev.target.files[0];
        var reader  = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function (e) {
            var image = new Image();
            image.src = e.target.result;
            image.onload = function(ev) {
                function one(){
                    // some code here...
                }

                function two(){
                    // some code here...
                }

                // etc..
            }
        }
    }
});

How can i do that ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code works. You are successfully running the code in the onloadend event, but your code merely declares two functions. It doesn’t run them. I have included some console.logs to illustrate my point.

let fileInput = document.getElementById('fileinput');
    fileInput.addEventListener('change', function(ev) {
    
    console.log('change event fired');  
  
    if(ev.target.files) {
        let file = ev.target.files[0];
        var reader  = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function (e) {
        
            console.log('loadEnd event fired');
        
            var image = new Image();

            function one() {
              console.log('image.load event fired');
              const canvas = document.getElementById("canvas");
              const context = canvas.getContext("2d");
              context.drawImage(image,0,0);
            };

            image.onload = one;
            image.src = e.target.result;
        }
    }
});
<form>
    <input type=file id=fileinput />
</form>

<canvas id=canvas width=300 height=300></canvas>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading