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

Konva.Transformer.getClientRect()最新版本不支持?如何获取其尺寸?

React-Konva 获取Transformer尺寸的替代方案

在最新版React-Konva中,transformer.getClientRect()方法已被弃用或行为变更,你可以通过以下两种方法获取Transformer的客户端尺寸:

方法1:利用getBoundingBox() + 坐标转换

通过Transformer的getBoundingBox()获取舞台坐标系下的位置和尺寸,再通过舞台的stageToClient()方法转换为浏览器客户端坐标:

const transformer = transformerRef.current;
const stage = transformer.getStage();
if (!stage) return;

const boundingBox = transformer.getBoundingBox();
// 转换左上角和右下角坐标到客户端坐标系
const topLeft = stage.stageToClient({ x: boundingBox.x, y: boundingBox.y });
const bottomRight = stage.stageToClient({
  x: boundingBox.x + boundingBox.width,
  y: boundingBox.y + boundingBox.height
});

// 组装完整的客户端矩形对象
const clientRect = {
  x: topLeft.x,
  y: topLeft.y,
  width: bottomRight.x - topLeft.x,
  height: bottomRight.y - topLeft.y,
  left: topLeft.x,
  top: topLeft.y,
  right: bottomRight.x,
  bottom: bottomRight.y
};

方法2:基于舞台DOM元素计算

直接获取舞台容器的DOM元素包围盒,结合Transformer的舞台尺寸计算客户端坐标:

const transformer = transformerRef.current;
const stage = transformer.getStage();
if (!stage) return;

const stageDom = stage.container();
const stageRect = stageDom.getBoundingClientRect();
const boundingBox = transformer.getBoundingBox();
const stageScaleX = stageRect.width / stage.width();
const stageScaleY = stageRect.height / stage.height();

const clientRect = {
  left: stageRect.left + boundingBox.x * stageScaleX,
  top: stageRect.top + boundingBox.y * stageScaleY,
  width: boundingBox.width * stageScaleX,
  height: boundingBox.height * stageScaleY,
  right: stageRect.left + (boundingBox.x + boundingBox.width) * stageScaleX,
  bottom: stageRect.top + (boundingBox.y + boundingBox.height) * stageScaleY
};

注意事项

  • 确保在组件挂载完成后(如useEffect钩子内)调用这些方法,避免Transformer未渲染导致返回无效值
  • 若Transformer未选中任何节点,getBoundingBox()会返回无效数据,需先判断选中状态

内容的提问来源于stack exchange,提问作者R.Muneeb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:54:22