Get base64 data of image inside a canvas

Viewed 30

I know this question is asked man times but my problem is this. I want to get data of image inside a canvas and get that! But when I change the image resource derived data does not change. In an other words it doesn't matter what image I use in my code. For best understanding my question my code is below.

<!DOCTYPE html>
<html>
    <body>

        <canvas id="viewport" style="border:1px solid #d3d3d3;"></canvas>

        <script>
            var canvas = document.getElementById('viewport'),
            context = canvas.getContext('2d');

            make_base();

            function make_base()
            {
              base_image = new Image();
              base_image.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
              base_image.onload = function(){
                context.drawImage(base_image, 0, 0);
              }
            }


            const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
            document.write('<br>');
            document.write(base64Canvas);

        </script>

    </body>
</html>

I the code above it does not matter what picture to use. The base64 data is same or every one. Any help?

1 Answers

you should capture the image after it has been loaded and drawn. this is asynchronous action so:

Update: please use an image locally or from an origin that allows CORS.

<!DOCTYPE html>
<html>

<body>

  <canvas id="viewport" style="border:1px solid #d3d3d3;"></canvas>

  <script>
    var canvas = document.getElementById('viewport'),
      context = canvas.getContext('2d');

    make_base();

    function make_base() {
      base_image = new Image();

      base_image.onload = function() {
        context.drawImage(base_image, 0, 0);

        const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
        console.log(base64Canvas);
      }
      base_image.crossOrigin = "anonymous"

      base_image.src = 'https://picsum.photos/200';

    }
  </script>

</body>

</html>

Related