Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 缩放图像以适合画布_Javascript_Html_Canvas_Html5 Canvas - Fatal编程技术网

Javascript 缩放图像以适合画布

Javascript 缩放图像以适合画布,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,我有一个表单,允许用户上传图像 加载映像后,我们对其执行一些缩放,以便在将其传递回服务器之前减小其文件大小 为此,我们将其放置在画布上并在画布上进行操作 此代码将在画布上渲染缩放图像,画布大小为320 x 240px: ctx.drawImage(img, 0, 0, canvas.width, canvas.height) 。。。其中canvas.width和canvas.height是基于原始图像大小的图像高度和宽度x比例因子 但当我使用代码时: ctx.drawImage(img, 0,

我有一个表单,允许用户上传图像

加载映像后,我们对其执行一些缩放,以便在将其传递回服务器之前减小其文件大小

为此,我们将其放置在画布上并在画布上进行操作

此代码将在画布上渲染缩放图像,画布大小为320 x 240px:

ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
。。。其中canvas.width和canvas.height是基于原始图像大小的图像高度和宽度x比例因子

但当我使用代码时:

ctx.drawImage(img, 0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height
。。。我只得到画布上的部分图像,在本例中是左上角。我需要整个图像“缩放”以适合画布,尽管实际图像大小大于320x240画布大小

对于上面的代码,宽度和高度是1142x856,这是最终的图像大小。我需要保持这个大小,以便在提交表单时将beck传递给服务器,但只希望在画布中为用户显示一个较小的视图

我错过了什么?谁能给我指一下正确的方向吗

非常感谢。请提供源图像(img)大小作为第一个矩形:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle
第二个矩形将是目标大小(源矩形将缩放到哪个大小)

更新2016/6:对于纵横比和定位(ala CSS的“封面”方法),请查看:

您在第二次调用时出错,将源的大小设置为目标的大小。
无论如何,我打赌您希望缩放图像具有相同的纵横比,因此您需要计算它:

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
我还假设您希望将图像居中,因此代码为:

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}
您可以在jsbin中看到它:

这太完美了,+1。快速提示-您缺少
drawImage()
函数的右括号。我的强迫症有点乱;)非常适合我的需要。它使我不必在表单边距更改时修改图像文件的大小/比例。谢谢;)非常感谢。我将Math.min()更改为Math.max(),以缩放和裁剪图像以适应画布。这很有帮助!但当我从小尺寸生成大图像时,这会生成模糊图像。它变得模糊了。。有解决办法吗?请感谢@gamealchest。通读这篇文章帮助我理解了如何得到一个缩小的图像,而这将花费我永远的时间来独自解决这个问题。谢谢@saadk;)