使用drawImage复制到HTML画布时裁剪的图像 [英] Image being clipped when copied to HTML canvas using drawImage

查看:50
本文介绍了使用drawImage复制到HTML画布时裁剪的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小片段,允许用户将图像拖到div容器(dropzone)中,然后在该div中创建画布,并将图像绘制到div中.但是,这确实起作用了,我根本无法弄清楚.问题是图像由于某种原因被裁剪.我可以确认图像已正确加载,原因是如果我附加一个图像对象而不是画布,那么它可以工作!显示整个图像.我还尝试将宽度和高度明确输入到 drawImage 参数中,但没有成功.

I am writing a small snippet that allows a user to drag an image into a div container (dropzone) and then creates a canvas in that div and paints the image into the div. But, this does now work and I simply am unable to figure it out. The problem is that the image is being clipped for some reason. I can confirm that the image is loaded correctly cause if instead of a canvas I append an image object, it works! The entire image is displayed. I have also tried explicitly entering the width and height into the drawImage parameters with no success.

function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  var dt = e.dataTransfer;
  var files = dt.files;

  if(files)
    readFile(files[0]);
}

function applyDataUrlToCanvas(dataUrl) {

  var canvas = document.getElementById('mainCanvas'),
  ctx = canvas.getContext("2d");

  var img = new Image();
  img.src = dataUrl;

  img.onload = function() {
    ctx.drawImage(img, 0, 0, img.width, img.height);
  };
}

//-----------------------------------------------------------------------------

function readFile(file) {

  var dropzone = document.getElementById('dropzone');

  for (var i = dropzone.childNodes.length - 1; i >= 0; i--) {
    dropzone.removeChild(dropzone.childNodes[i]);
  }

  var canvas = document.createElement('canvas');
  canvas.id = 'mainCanvas';
  canvas.style.display = "block";
  canvas.style.margin = "auto";
  dropzone.appendChild(canvas);

  var reader = new FileReader();

  reader.readAsDataURL(file);

  reader.onload = function(e) {
    applyDataUrlToCanvas(this.result);
  };
}

推荐答案

您没有在任何地方指定 Canvas 元素的大小(至少没有在此处显示的代码中指定).

You are not specifying the size of the Canvas element anywhere (at least not in the code shown here).

如果未指定画布大小,则默认为300 x 150像素.

If size for canvas isn't specified it will default to 300 x 150 pixels.

您可以随时更新画布的大小,因此,如果图像大小未知,在此处执行以下操作可能是一个好主意:

You can update the canvas' size at anytime so here it might be a good idea to do the following if size of image is unknown:

img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
};

使用 drawImage 时不指定尺寸将使用图像的原始尺寸,因此这里没有必要,因为我们会知道画布将与图像一样大.

Not specifying size when using drawImage will use the original size of the image so here it's not necessary as here we 'll know the canvas will be as big as the image.

这篇关于使用drawImage复制到HTML画布时裁剪的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆