canvas.drawImage blows the cropped imaged out of proportion

北慕城南 提交于 2019-12-11 11:25:41

问题


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

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:


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


来源:https://stackoverflow.com/questions/30884082/canvas-drawimage-blows-the-cropped-imaged-out-of-proportion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!