【问题标题】:Drawing Image onto Canvas Stretches Image?在画布上绘制图像会拉伸图像?
【发布时间】:2013-10-28 12:09:02
【问题描述】:

我有这个代码(从网上偷来的):

function readIt() {
  var reader = new FileReader();
    reader.onload = (function(e) {
      var img = new Image();
      img.src = e.target.result;
      var c = document.getElementById("canvas");
      var ctx = c.getContext("2d");
      ctx.drawImage(img, 0, 0);
    }
  );
  reader.readAsDataURL(document.getElementById('userImage').files[0]);
}

这在一定程度上起作用。画布的宽度和高度设置为图像的大小,但只显示图像的左上角 - 它似乎被拉伸,因此它适合分配给画布的所有空间(足以显示整个图像 - 615px x 615px )。

如果我添加一个与画布大小相同的 元素,并将 src 指向文件系统中的图像,它看起来很完美。

我使用的是 Chrome,但在 Firefox 中显示相同。

提前致谢。

【问题讨论】:

  • 问题是使用 CSS 来指定画布的高度和宽度。你知道为什么吗?

标签: html5-canvas


【解决方案1】:

几个想法:

  • 使用 Image 的 onload 方法,让图像有足够的时间在使用前加载。
  • 如果您使用 css 调整画布大小,请不要。而是调整画布元素本身的大小。

这里有一些示例代码:

var img=new Image();
img.onload=function(){

    var c=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // resize the canvas element to the same size as the image
    // DON'T RESIZE WITH CSS -- your results will appear stretched
    c.width=img.width;
    c.height=img.height;

    // draw the image onto the canvas
    ctx.drawImage(img,0,0);

}
img.src=e.target.result;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2019-05-12
    • 2011-01-11
    • 2013-07-20
    • 1970-01-01
    相关资源
    最近更新 更多