drgd73844 2014-03-10 18:14
浏览 260
已采纳

调整图像大小以使其适合特定大小的画布并保持纵横比

I have some boxes that have the dimensions of 340 x 170 and users will be uploading images that need to be displayed into these boxes; however I'm not really sure how to go about resizing them so they don't lose aspect ratio and always fit in the box.

Requirements..

  • Canvas should always be 340 x 170
  • Image can't lose aspect ratio
  • If the image has a greater width than height than it should be as wide as possible to 340px
  • Ditto to the height
  • Should always be able to see the whole image in the canvas

Normally you would just resize by the largest side, however this obviously won't work as then you will end up with a larger height than 170px if the height is close to the width.

  • 写回答

2条回答 默认 最新

  • douyaosi3164 2014-03-10 18:22
    关注

    What you really care about is the relationship between the image's aspect ratio and the canvas' aspect ratio.

    Here's some self-explanatory code (would be glad to add explanation if needed):

    var imgRatio = img.width / img.height; // Image aspect ratio
    var canvasRatio = canvas.width / canvas.height; // Canvas aspect ratio
    
    var resultImageH, resultImageW; // Variables that hold the result of the sizing algorithm
    
    if(imgRatio < canvasRatio) {
        resultImageH = canvas.height;
        resultImageW = resultImageH * imgRatio;
    }
    else {
        resultImageW = canvas.width;
        resultImageH = resultImageW / imgRatio;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建