Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

第 82 期(算法-数学):如何将一张图片完全显示在容器里 #85

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

如何将一张图片完全显示在容器里?当图片尺寸小于容器时,直接显示就行了,但是当图片尺寸大于容器时,就要设法缩放图片以完全装入容器,图片要尽可能的大,并保持宽高比例(图片不能变形)。

如果是背景图片,为其容器设置 background-size: contain CSS 声明即可;如果是 <img> 图片的话,可以利用 object-fit 来实现,详情:第 35 期(W3C 标准-CSS-布局排版):图片等比缩放匹配父容器尺寸

我们本期讨论的是使用算法来解决这个问题,像 canvas 绘制图片这种场景就需要这样的解决方案。

思路:

  1. 图片载入成功后获取其宽高;
  2. 判断宽高是否小于或等于容器宽高,如是,则直接按原图尺寸显示即可;
  3. 如图片宽高大于容器宽高(宽度大于容器宽高,或高度大于容器宽高,或两者皆有之),取图片宽、高最大的一个进行等比缩放;
  4. 缩放完毕后再进行一次与容器尺寸的判断(不排除有些变态的图);
  5. 如尺寸依然大于容器尺寸,则以大于容器的宽度或高度为基准,再进行一次等比缩放;
  6. 最终将缩放完成的图显示出来。

照片操作

代码实现参考:

> 在线 Demo <

const temp = {
  dWidth: 0
  dHeight: 0
};

if (boxWidth >= imgWidth && boxHeight >= imgHeight) {  // 照片小于等于容器尺寸
  temp.dWidth = imgWidth;
  temp.dHeight = imgHeight;
} else {
  if (imgWidth >= imgHeight) {  // 宽度优先
    temp.dWidth = boxWidth;
    temp.dHeight = imgHeight * boxWidth / imgWidth;
  } else {  // 高度优先
    temp.dHeight = boxHeight;
    temp.dWidth = imgWidth * boxHeight / imgHeight;
  }

  // 缩放后依然大于容器
  if (temp.dWidth > boxWidth) {
    temp.dHeight = temp.dHeight * boxWidth / temp.dWidth;
    temp.dWidth = boxWidth;
  } else if (temp.dHeight > boxHeight) {
    temp.dWidth = temp.dWidth * boxHeight / temp.dHeight;
    temp.dHeight = boxHeight;
  }
}

console.log(temp);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.