We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
如何将一张图片完全显示在容器里?当图片尺寸小于容器时,直接显示就行了,但是当图片尺寸大于容器时,就要设法缩放图片以完全装入容器,图片要尽可能的大,并保持宽高比例(图片不能变形)。
如果是背景图片,为其容器设置 background-size: contain CSS 声明即可;如果是 <img> 图片的话,可以利用 object-fit 来实现,详情:第 35 期(W3C 标准-CSS-布局排版):图片等比缩放匹配父容器尺寸
background-size: contain
<img>
object-fit
我们本期讨论的是使用算法来解决这个问题,像 canvas 绘制图片这种场景就需要这样的解决方案。
> 在线 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);
The text was updated successfully, but these errors were encountered:
No branches or pull requests
如何将一张图片完全显示在容器里?当图片尺寸小于容器时,直接显示就行了,但是当图片尺寸大于容器时,就要设法缩放图片以完全装入容器,图片要尽可能的大,并保持宽高比例(图片不能变形)。
如果是背景图片,为其容器设置
background-size: contain
CSS 声明即可;如果是<img>
图片的话,可以利用object-fit
来实现,详情:第 35 期(W3C 标准-CSS-布局排版):图片等比缩放匹配父容器尺寸我们本期讨论的是使用算法来解决这个问题,像 canvas 绘制图片这种场景就需要这样的解决方案。
思路:
代码实现参考:
> 在线 Demo <
The text was updated successfully, but these errors were encountered: