简体   繁体   English

canvas.drawImage将裁剪的图像吹成比例

[英]canvas.drawImage blows the cropped imaged out of proportion

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. 大小为4800x320,带有html5 canvas.drawImage()并尝试从中裁剪出部分480x320的图像,画布会将图像放大。

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? 有人知道为什么吗?

Canvas' default bitmap size is 300x150 pixels. Canvas的默认位图大小为300x150像素。 Setting the CSS size won't change the bitmap size. 设置CSS大小不会更改位图大小。 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. 如果不是,则将拉伸位图以填充元素CSS大小。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM