Rajiv Nair
Rajiv Nair

Reputation: 187

Image being clipped when copied to HTML canvas using 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);
  };
}

Upvotes: 1

Views: 2312

Answers (2)

Kazzo
Kazzo

Reputation: 3

I have canvas width and heihgt set to 100% in css setting so:

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

in page load event do the trick

Upvotes: 0

user1693593
user1693593

Reputation:

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

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

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.

Upvotes: 9

Related Questions