缩放图像以适合画布

新手上路,请多包涵

我有一个允许用户上传图片的表单。

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

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

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

 ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

… 其中 canvas.width 和 canvas.height 是图像高度和宽度 xa 缩放因子,基于原始图像的大小。

但是当我去使用代码时:

 ctx.drawImage(img, 0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height

…我只在画布上获得部分图像,在这种情况下是左上角。尽管实际图像尺寸大于 320x240 画布尺寸,但我需要将整个图像“缩放”以适合画布。

所以对于上面的代码,宽度和高度都是 1142x856,因为这是最终的图像尺寸。我需要保持该大小以在提交表单时将其传递给服务器,但只希望它的较小视图出现在用户的画布中。

我在这里想念什么?谁能指出我正确的方向?

提前谢谢了。

原文由 dradd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

提供源图像 (img) 大小作为第一个矩形:

 ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

第二个矩形将是目标大小(将缩放到什么源矩形)。

20166 更新:对于纵横比和定位(ala CSS 的“覆盖”方法),请查看:

模拟背景尺寸:覆盖在画布中

原文由 user1693593 发布,翻译遵循 CC BY-SA 3.0 许可协议

您在第二次调用时犯了错误,将源的大小设置为目标的大小。

无论如何,我敢打赌你想要缩放图像的纵横比相同,所以你需要计算它:

 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 中看到它: http ://jsbin.com/funewofu/1/edit?js,output

原文由 GameAlchemist 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题