javascripthtmlvue.jshtml5-canvas

canvas.drawImage crops image


Hello I have the following image:

enter image description here

with size 750x554

I load the iamge into a img tag, of the following way:

 <input type="file" accept="image/*"
        onchange="document.getElementById('character').src = window.URL.createObjectURL(this.files[0]);">

      <img id="character" alt="your image" width="100" height="100" />

And in order to convert this image into a base64 I use canvas with the following code:

  let canvas = document.createElement("canvas");

  canvas.width = img.width
  canvas.height = img.height

  let ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  let dataURL = canvas.toDataURL("image/png");

But the result that I get is a cropped image as you can see here

enter image description here

How can solve this, and get the image in base64?

Thanks.


Solution

  • you need to set the canvas to the size of the image and you need to wait for the image to actually load before trying to draw it.

    document.querySelector('input').addEventListener('change', function() {
      const url = window.URL.createObjectURL(this.files[0]);
      const img = document.getElementById('character');
      img.addEventListener('load', function() {
        let canvas = document.createElement("canvas");
    
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
    
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
    
        let dataURL = canvas.toDataURL("image/png");
        
        // show image
        const i = new Image();
        i.src = dataURL;
        document.body.appendChild(i);
      });
      img.src = url;
    });
    <input type="file" accept="image/*">
    <img id="character" alt="your image" width="100" height="100" />