canvas.drawImage blows the cropped imaged out of proportion

234 views Asked by At

When rendering the following image (right-click + view image to see full size):

http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png

of size 4800x320 with html5 canvas.drawImage() and trying to crop a partial 480x320 image from it, the canvas blows the image up.

Here is my code:

var canvas = document.createElement('canvas');
canvas.setAttribute('id', 'my-canvas');
canvas.style.width = 480;
canvas.style.height = 320;
canvas.style.display = 'block';

document.body.appendChild(canvas);

var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
  var c=document.getElementById('my-canvas');
  var ctx=c.getContext('2d');
  ctx.drawImage(img,480,0,480,320,0,0,480,320);
}

also, when I draw the image to a smaller scale, it suddenly fits:

var canvas = document.createElement('canvas');
canvas.setAttribute('id', 'my-canvas');
canvas.style.width = 480;
canvas.style.height = 320;
canvas.style.display = 'block';

document.body.appendChild(canvas);

var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
  var c=document.getElementById('my-canvas');
  var ctx=c.getContext('2d');
  ctx.drawImage(img,480,0,480,320,0,0,240,160);
}

does anyone knows why that is?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Canvas' default bitmap size is 300x150 pixels. Setting the CSS size won't change the bitmap size. The bitmap is set with its own width/height properties/attributes directly on the element. If not the bitmap will be stretched to fill the element CSS size.

Change these:

canvas.style.width = 480;
canvas.style.height = 320;

to

canvas.width = 480;
canvas.height = 320;

You can also setup your code to reuse the context:

//var c=document.getElementById('my-canvas'); // you already have this as canvas
var ctx=canvas.getContext('2d');              // global/parent scope

var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
  ctx.drawImage(img,480,0,480,320,0,0,480,320);
}