慕莱坞森
如果您正在寻找一种适用于大多数情况的简单解决方案,并且还包括类似CSS contain的功能,请尝试以下方法:function fit(contains) { return (parentWidth, parentHeight, childWidth, childHeight, scale = 1, offsetX = 0.5, offsetY = 0.5) => { const childRatio = childWidth / childHeight const parentRatio = parentWidth / parentHeight let width = parentWidth * scale let height = parentHeight * scale if (contains ? (childRatio > parentRatio) : (childRatio < parentRatio)) { height = width / childRatio } else { width = height * childRatio } return { width, height, offsetX: (parentWidth - width) * offsetX, offsetY: (parentHeight - height) * offsetY } }}export const contain = fit(true)export const cover = fit(false)内部比例的略微修改版本,包括比例和偏移用法:import {cover, contain} from './intrinsic-scale'const { offsetX, offsetY, width, height} = cover(parentWidth, parentHeight, imageWidth, imageHeight)// or...const { offsetX, offsetY, width, height} = contain(parentWidth, parentHeight, imageWidth, imageHeight)ctx.drawImage(image, offsetX, offsetY, width, height)