无法编辑 Fabric.js 表格单元格中的文本

问题描述 投票:0回答:2

我正在开发一个项目,其中使用 Fabric.js 创建一个表,每个单元格中都包含 **可编辑 **文本。我可以创建表格、移动表格并调整其大小,但在编辑单元格中的文本时遇到问题。

这是我正在使用的代码:

function createTable(rows: number, cols: number, cellWidth: number, cellHeight: number) {
  const table = new fabric.Group([]);

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      const cell = new fabric.Rect({
        width: cellWidth,
        height: cellHeight,
        fill: 'transparent',
        stroke: 'black',
        strokeWidth: 1,
        selectable: false,
        left: j * cellWidth,
        top: i * cellHeight,
      });

      const text = new fabric.Textbox(`Cell ${i + 1},${j+1}`, {
        left: j * cellWidth + 5,
        top: i * cellHeight + 5,
        fontSize: 16,
        width: cellWidth - 10, // Adjusting for padding
        height: cellHeight - 10, // Adjusting for padding
        fontFamily: 'Arial',
        editable: true,
      });

      table.addWithUpdate(cell);
      table.addWithUpdate(text);
    }
  }

  return table;
}

const table = createTable(+rows, +cols, +cellWidth, +cellHeight);
canvas?.add(table);

我已经为文本框设置了

editable: true
,但我仍然无法编辑单元格中的文本。我是否遗漏或做错了什么?任何帮助或建议将不胜感激。谢谢!

reactjs typescript fabricjs
2个回答
0
投票

我想我已经找到了解决方案。 您必须添加以下代码:

const table = new fabric.Group([]);
table.evented = true;
table.subTargetCheck = true;    

您必须将以下代码添加到循环中的每个文本中:

var dirtyGroup = function() {
  text.group.dirty = true;
  canvas.renderAll();
};
text.on("changed", dirtyGroup);
text.on("editing:exited", dirtyGroup);
text.on("selection:changed", dirtyGroup);

并且您还必须弄清楚将使用什么方法使用

text.exitEditing()
方法退出编辑;


-1
投票

您好,您能解决这个问题吗?我也需要在fabricJs中创建一个类似excel/word的表格

© www.soinside.com 2019 - 2024. All rights reserved.