0

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>
Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42

1 Answers1

1

Give the below code a try.

img.src = ""+reader.result;
img.onload = function() {
    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  );
}
Debabrata Patra
  • 498
  • 3
  • 15