I am searching, since three days, How I could create a button to open a picture in the canvas of HTML5 with vanilla javascript.
I have this code that I change and re-re-change, and that never work correctly, often that open my picture one time and if I re-click on my button I have an error, if I relaunch the script that work or not., at a moment that worked I put an alert(), In the 'reader.addEventListener', I don't understand correctly addEventListener, and I am re-reading the documentation.
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" >
    </head>
    <body>
        <canvas id="canvasToDraw"></canvas>
        <input type="file" onclick="openPicture()"></input>
        <script>
        function openPicture()
        {
            var file = document.querySelector('input[type=file]').files[0];
            var reader  = new FileReader();
            reader.readAsDataURL(file);
            // 
            img = new Image();
            img.id = "bufferPicture";
            document.body.appendChild( img);
            reader.addEventListener('load', function() {                        
                    img.src = ""+reader.result;
            var height = img.height;
            var width = img.width;
            document.getElementById("canvasToDraw").width = width;
            document.getElementById("canvasToDraw").height = height;
            var contextCanvas = document.getElementById("canvasToDraw").getContext("2d");
            contextCanvas.drawImage(    document.getElementById("bufferPicture"), 0, 0  );
            });
            // remove the picture
            // document.body.removeChild(document.getElementById("bufferPicture"));
        }
        </script>
    </body>
</html>
 
     
    