You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取设置object-fit:contain的<img>标签内实际渲染的图片尺寸

example

解决方案

object-fit: contain规则下的内部图片渲染尺寸可通过原始比例 + 容器尺寸计算得到,具体实现如下:

核心逻辑

  • naturalWidth/naturalHeight返回图片原始像素尺寸,不受容器和渲染规则影响
  • clientWidth/clientHeight返回img标签本身的渲染尺寸,也就是占满容器的标签尺寸
  • contain规则会保持图片原始比例,将图片完整缩放至容器内,最终缩放比例取宽、高两个方向缩放比的最小值

完整代码

const imgEl = document.querySelector('img') // 替换为目标img元素的选择器

function getContainRenderedSize(img) {
  // 处理图片未加载完成的情况
  if (!img.complete) {
    img.addEventListener('load', () => getContainRenderedSize(img), { once: true })
    return
  }
  const { naturalWidth, naturalHeight, clientWidth, clientHeight } = img
  // 计算两个方向的缩放比例
  const widthRatio = clientWidth / naturalWidth
  const heightRatio = clientHeight / naturalHeight
  // 取较小值为实际缩放比例
  const renderScale = Math.min(widthRatio, heightRatio)
  // 返回四舍五入后的实际渲染尺寸
  return {
    width: Math.round(naturalWidth * renderScale),
    height: Math.round(naturalHeight * renderScale)
  }
}

// 调用方法获取结果
const renderedImgSize = getContainRenderedSize(imgEl)
console.log(renderedImgSize)

此前方法无效的原因

  • naturalWidth/naturalHeight返回的是原图尺寸,不是渲染缩放后的尺寸
  • clientWidth/width返回的是img标签本身的尺寸,不是内部缩放后的图片尺寸

内容的提问来源于stack exchange,提问作者A.Burdonskaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 14:15:02