Konvajs:如何解决特殊的“选择和转换:调整文本大小”问题?

1. 背景:

我使用konvajs创建一个“table”组件:

结构:

       Stage
         |     
       Layer       
         |            
   +-----+--------------+    
   |                    |
Group(tableGroup) Group(tableGroup)
                        |
         +--------------+--------+
         |                       |
      Group(cellGroup)     Group(cellGroup)
         |
    +----+----+
    |         |
Shape(Rect)  Shape(Text)

图像:

img

2. 目标:

我希望每个文本形状都具有宽度自适应性。我在konvajs的官方文件中找到了它:

如何使用变换工具更改文本的宽度? https://konvajs.org/docs/select_and_transform/Resize_Text.html

方案 1: 将所有“cellGroup”添加到“transformer”

// My code
tableGroup.on('click', function (e) { // Click the selected table
   tr.nodes([])
   tableGroup.getChildren().map(function(item) {
       tr.nodes(tr.nodes().concat(item)); // Add all cellGroups to transformer
       item.off('transform')
       item.on('transform', (e) => {
           item.setAttrs({
               width: item.width() * item.scaleX(),
               height: item.height() * item.scaleY(),
               scaleX: 1,
               scaleY: 1,
           });
           item.getChildren().map(function(child){
               child.setAttrs({
                    width: item.width() * item.scaleX(),
                    height: item.height() * item.scaleY(),
                    scaleX: 1,
                    scaleY: 1,
               });
           })
       })
    })
});

方案 2: 将“tableGroup”添加到“transformer”

// My code
tableGroup.on('click', function (e) { // Click the selected table
   tr.nodes([tableGroup]) // Add all tableGroup to transformer
   tableGroup.on('transform', (e) => {
       tableGroup.getChildren().map(function(item) {
           item.setAttrs({
               width: item.width() * item.scaleX(),
               height: item.height() * item.scaleY(),
               scaleX: 1,
               scaleY: 1,
           });
           item.getChildren().map(function(child){
               child.setAttrs({
                    width: item.width() * item.scaleX(),
                    height: item.height() * item.scaleY(),
                    scaleX: 1,
                    scaleY: 1,
               });
           })
        })
     })
});

结论:方案1是可行的,但方案2是不可行的。我的要求是将“tableGroup”添加到转换器“transformer”中,并实现文本宽度的自适应。找到解决方案,非常感谢。

3. 其他:

问:为什么必须在“transformer”中添加“tableGroup”?

答:因为当用“transformer”移动“Group”或“Shape”时,“Group”或“Shape”的坐标(x,y)会发生变化。我不想更改“cellGroup”的坐标,我想更改“tableGroup”(x,y)的坐标。或者你有一个更好的解决方案。找到解决方案,非常感谢。