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

解决方案
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
相关产品推荐
相关产品推荐

