canvas.drawImage将裁剪的图像吹成比例 [英] canvas.drawImage blows the cropped imaged out of proportion
问题描述
渲染以下图像时(右键单击并查看图像以查看完整大小):
When rendering the following image (right-click + view image to see full size):
大小为4800x320, html5 canvas.drawImage()
并尝试从中裁剪出部分480x320的图像,画布将图像放大。
of size 4800x320 with html5 canvas.drawImage()
and trying to crop a partial 480x320 image from it, the canvas blows the image up.
这是我的代码:
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);
}
有人知道为什么吗?
推荐答案
画布的默认位图大小为300x150像素。设置 CSS 的大小不会更改位图的大小。位图具有自己的width / height属性/属性,直接在元素上设置。如果不是,则将拉伸位图以填充元素CSS大小。
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.
更改以下内容:
canvas.style.width = 480;
canvas.style.height = 320;
到
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);
}
这篇关于canvas.drawImage将裁剪的图像吹成比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!