首页 > 解决方案 > 以编程方式更新 FabricJS iText 的问题

问题描述

我已经在这个问题上停留了几个小时,我看不出有什么明显的原因说明我为什么不能这样做。

我正在使用 FabricJS 创建可编辑的画布。我目前正在添加文本功能,因此当用户单击工具图标然后单击画布时,它将放置一个带有占位符文本的 iText 对象:“在此处键入...”。

我在 Fabric 对象上添加了一个名为placeholderPresent. 然后我在画布上添加了一个监听器,如下所示:

this.canvas.on('text:changed', (data) => {

            let textObject = data.target;

            textObject.set('dirty', true);

            // If the user has just created this text and is now writing in it, remove the placeholder
            if(textObject.placeholderPresent) {
                textObject.set('text', textObject.text.replace('Type here...', ""));
                textObject.set('dirty', true);
                textObject.set('placeholderPresent', false);
            }

            this.canvas.renderAll();
        });

这样做的想法是,当用户在放置文本框后第一次输入文本框时,它会立即删除占位符文本。

我遇到的问题是,当用户键入他们的第一个字符时,这确实有效,但是当他们键入第二个字符时,它会在 iText 对象中当前的文本末尾添加“Type here ...”。

我的猜测是这是由于某种缓存,但我试图在多个地方将 'dirty' 设置为 true 以强制 FabricJS 重新渲染,但这仍然不起作用。

关于可能导致这种情况的任何想法?提前致谢。

标签: javascriptfabricjsfabricjs2

解决方案


根据您的描述,我不清楚您要做什么或为什么要在此处使用“更改”事件,因此我可能会误解您的要求。

您可以在创建 的实例时设置默认文本iText。您还可以选择默认文本,以便在用户开始键入时替换默认文本。您可以使用其他事件(例如“editing:exited”)来处理检查用户输入的文本并在iText实例为空时恢复默认文本等。

下面是我的“工具”类包装器中的一个方法iText——也许它会有所帮助。

onMouseDown(evt) {
    this.owner.toolActionBegin()
    this.isMouseDown = true
    this.startPt = this.canvas.getPointer(evt.e);

    this.object = new fabric.IText("New text",
      {
        left: this.startPt.x,
        top: this.startPt.y,
        fill: this.owner.textColor,
        selectable: true,
        fontFamily: 'arial',
        fontSize: this.owner.fontSize,
        editable: true,
        selectionBackgroundColor: "rgb(255,255,255)",
        perPixelTargetFind: false,
        hasBorders: true,
        hasControls: true,
      });

    
      this.object.setControlsVisibility({
        tl: true,
        tr: true,
        br: true,
        bl: true,
        ml: false,
        mt: false,
        mr: false,
        mb: false,
        mtr: true
      })

    this.canvas.add(this.object)
    this.canvas.on("mouse:up", this.onMouseUp);
    this.canvas.on("editing:exited", this.onExitEditing);
  }

推荐阅读