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

在Konva.js中模拟object-fit:contain实现图片居中适配

实现图片在矩形内完整适配(object-fit: contain)并居中

你当前的代码仅计算了缩放后的图片尺寸,但未处理居中偏移量,因此图片无法在矩形容器内居中。要完整模拟object-fit: contain的效果,需要同时计算缩放比例和居中偏移坐标,修正后的实现如下:

const containerWidth = size.width;
const containerHeight = size.height;
const imgWidth = image.width;
const imgHeight = image.height;

// 计算适配容器的缩放比例:取较小值,确保图片完整显示(对应object-fit: contain)
const scaleX = containerWidth / imgWidth;
const scaleY = containerHeight / imgHeight;
const scale = Math.min(scaleX, scaleY);

// 计算缩放后的图片实际尺寸
const scaledImgWidth = imgWidth * scale;
const scaledImgHeight = imgHeight * scale;

// 计算居中偏移量:容器与缩放后图片的差值的一半,实现水平/垂直居中
const offsetX = (containerWidth - scaledImgWidth) / 2;
const offsetY = (containerHeight - scaledImgHeight) / 2;

return {
  scaledWidth: scaledImgWidth,
  scaledHeight: scaledImgHeight,
  offsetX: offsetX,
  offsetY: offsetY
};

关键逻辑说明:

  • 缩放比例选择:使用Math.min(scaleX, scaleY),保证图片的宽高都不会超出容器边界,让图片完整适配容器内部,这是object-fit: contain的核心要求。
  • 居中偏移计算:通过容器尺寸与缩放后图片尺寸的差值除以2,得到水平和垂直方向的偏移量,将图片定位在容器的中心位置。

内容的提问来源于stack exchange,提问作者EgorkZe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:12:05