canvas.drawImage裁剪图像

问题描述 投票:1回答:2

您好,我有以下图像:

enter image description here

尺寸为750x554

我通过以下方式将iamge加载到img标签中:

 <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" />

并且为了将该图像转换为base64,我使用带有以下代码的canvas:

  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");

但是我得到的结果是裁剪的图像,您可以在这里看到

enter image description here

如何解决这个问题,并在base64中获得图像?

谢谢。

javascript html vue.js html5-canvas
2个回答
1
投票

添加此行

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

呼叫drawImage之前


0
投票

我认为这里的图像标签存在问题,因为您将图像的宽度和高度指定为100

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

因此,您可以为图像标签提供实际的高度和宽度。

快乐编码!

© www.soinside.com 2019 - 2024. All rights reserved.