LiteGraph实现自定义节点内显示图片和文字并动态更新显示效果代码

代码语言:html

所属分类:其他

代码描述:LiteGraph实现自定义节点内显示图片和文字并动态更新显示效果代码

代码标签: LiteGraph 自定义 节点 显示 图片 文字 动态 更新

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />
<link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/litegraph.1.0.css">
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/litegraph.1.0.js"></script>
</head>
<body>
    <canvas width="1200" height="900" id="graphcanvas">
       
    </canvas>
    
    <script>
// 自定义节点类
function CustomNode() {
    this.addInput("input", "number");
    this.addOutput("output", "number");
    this.properties = { text: "Default text", imageUrl: "", value: 0 };
    this.image = null;
    this.size = [200, 100]; // 初始尺寸
}

// 继承LiteGraph.LGraphNode
CustomNode.prototype = Object.create(LiteGraph.LGraphNode.prototype);
CustomNode.prototype.constructor = CustomNode;

// 设置节点标题
CustomNode.title = "CustomNode";

// 处理输入数据并更新属性值
CustomNode.prototype.onExecute = function() {
    var input = this.getInputData(0);
    if (input !== undefined) {
        this.properties.value = input;
    }
    this.setOutputData(0, this.properties.value);
};

// 加载图片
CustomNode.prototype.loadImage = function(url) {
    var self = this;
    var img = new Image();
    img.onload = function() {
        self.image = img;
        self.updateSize();
        self.setDirtyCanvas(true);
    };
    img.src = url;
};

// 更新节点尺寸
CustomNode.prototype.updateSize = function() {
    var textHeight = 50; // 固定文本高度
    var imgHeight = this.image ? this.image.height : 0;
    var padding = 20; // 内边距
    this.size[1] = textHeight + imgHeight + padding;
};

// 绘制节点并显示文字或图片
CustomNode.prototype.onDrawForeground = function(ctx) {
    // 确保父类的 onDrawForeground 方法存在
    if (LiteGraph.LGraphNode.prototype.onDrawForeground) {
        LiteGraph.LGraphNode.prototype.onDrawForeground.call(this, ctx);
    }

    // 保存当前绘图状态
    ctx.save();

    // 设置剪切区域为节点内部
    ctx.beginPath();
    ctx.rect(0, 0, this.size[0], this.size[1]);
    ctx.clip();

    // 绘制文.........完整代码请登录后点击上方下载按钮下载查看

网友评论0