You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

ComfyUI自定义节点前端问题:节点ID异常与额外文本显示实现

在ComfyUI自定义节点上显示额外文本的解决方案

先解决nodeCreatednode.id为-1的问题

nodeCreated触发时,节点还没完成后端同步注册,此时的id是临时占位的-1。别用这个id做映射,直接用节点的**uuid**——每个节点实例生成时就有唯一且不变的uuid:

const nodeExtraTextMap = new Map();

app.registerExtension({
  nodeCreated(node) {
    // 用uuid作为键存储要显示的文本
    nodeExtraTextMap.set(node.uuid, "你要展示的额外文本");
  }
});

显示额外文本的三种可行方案

方案1:优化你当前的onDrawForeground思路

用uuid做映射后,直接在绘制回调里匹配即可,不用再纠结id:

app.registerExtension({
  onDrawForeground(ctx) {
    graph._nodes.forEach(node => {
      const extraText = nodeExtraTextMap.get(node.uuid);
      if (extraText) {
        // 自定义文本样式
        ctx.fillStyle = "#ff4444";
        ctx.font = "14px Arial";
        // 绘制位置:节点标题下方10px处,可自行调整坐标
        ctx.fillText(extraText, node.pos[0] + 10, node.pos[1] + 40);
      }
    });
  }
});

方案2:直接在自定义节点内部添加UI元素(最原生)

如果是你自己开发的节点,直接在节点类里定义额外文本控件,不用依赖全局回调:

class MyCustomNode extends LiteGraph.LiteGraphNode {
  constructor(title) {
    super(title);
    // 自定义属性存储额外文本
    this.extraText = "默认提示文本";
    // 在节点顶部添加文本标签
    this.widgets_up.push({
      type: "label",
      name: "extra_info",
      text: this.extraText
    });
  }

  // 动态更新文本的方法
  updateExtraText(newText) {
    this.extraText = newText;
    this.widgets_up.find(w => w.name === "extra_info").text = newText;
    this.setDirtyCanvas(true);
  }
}

// 注册节点
LiteGraph.registerNodeType("my_nodes/custom_node", MyCustomNode);

这种方式更贴合ComfyUI的节点开发规范,无需全局监听,直接在节点内部管理UI。

方案3:改用nodeAdded回调获取有效id

如果一定要用节点id,就换nodeAdded回调——这个时机节点已经完成后端注册,id是有效的正整数:

const nodeExtraTextMap = new Map();

app.registerExtension({
  nodeAdded(node) {
    // 此时node.id已为后端分配的有效id
    nodeExtraTextMap.set(node.id, "你的额外文本");
  },

  onDrawForeground(ctx) {
    graph._nodes.forEach(node => {
      const extraText = nodeExtraTextMap.get(node.id);
      if (extraText) {
        ctx.fillStyle = "#00cc66";
        ctx.font = "14px Arial";
        // 绘制在节点底部下方
        ctx.fillText(extraText, node.pos[0] + 10, node.pos[1] + node.size[1] + 15);
      }
    });
  }
});

注意事项

  • 若修改第三方节点,优先选方案1或3;自己开发节点优先方案2。
  • 绘制文本时可利用node.size[1]适配节点高度,避免文本位置偏移。

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

火山引擎 最新活动