简体   繁体   English

canvas.drawImage 裁剪图像

[英]canvas.drawImage crops image

Hello I have the following image:您好,我有以下图片:

在此处输入图像描述

with size 750x554尺寸为 750x554

I load the iamge into a img tag, of the following way:我通过以下方式将 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" />

And in order to convert this image into a base64 I use canvas with the following code:为了将此图像转换为 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");

But the result that I get is a cropped image as you can see here但是我得到的结果是一个裁剪的图像,你可以在这里看到

在此处输入图像描述

How can solve this, and get the image in base64?如何解决这个问题,并获得 base64 中的图像?

Thanks.谢谢。

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.您需要将 canvas 设置为图像的大小,并且在尝试绘制之前需要等待图像实际加载。

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

I think here problem is with your image tag since you have specified the image's width and height as 100我认为这里的问题在于您的图像标签,因为您已将图像的宽度和高度指定为100

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

So instead of this just give the actual height and width to image tag.因此,只需为图像标签提供实际的高度和宽度,而不是这样。

Happy Coding !!!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM