You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在mxGraph中获取已放置图形的标签名称并统计展示?

mxGraph 获取画布图形统计的实现方案

核心思路

通过mxGraph的API获取画布上所有图形顶点,遍历统计不同形状的数量,最后转换为中文描述展示。

实现代码

1. 图形统计函数

function countShapes() {
    // 假设你的mxGraph实例变量为graph
    const graph = window.graph;
    // 获取画布根节点下的所有图形顶点(自动排除连接线)
    const vertices = graph.getChildVertices(graph.getDefaultParent());
    
    // 初始化各图形计数
    const shapeCounter = {
        ellipse: 0,
        rectangle: 0
        // 可按需扩展其他图形类型,比如triangle、rhombus等
    };

    // 遍历图形并统计
    vertices.forEach(cell => {
        const cellStyle = graph.getCellStyle(cell);
        // 从样式中取图形类型,默认值为矩形
        const shapeType = cellStyle.shape || 'rectangle';
        
        if (shapeCounter.hasOwnProperty(shapeType)) {
            shapeCounter[shapeType]++;
        }
    });

    // 组装中文结果文本
    const resultParts = [];
    if (shapeCounter.ellipse > 0) {
        resultParts.push(`${shapeCounter.ellipse}个椭圆`);
    }
    if (shapeCounter.rectangle > 0) {
        resultParts.push(`${shapeCounter.rectangle}个矩形`);
    }

    // 展示结果,这里用alert示例,可替换为DOM元素渲染
    const resultText = resultParts.length ? `存在${resultParts.join('和')}` : '画布上无图形';
    alert(resultText);
}

2. 绑定按钮触发事件

给页面按钮添加点击逻辑:

<button onclick="countShapes()">统计画布图形</button>

关键说明

  • getChildVertices():专门获取画布中的图形顶点,自动过滤掉连接线等非图形元素
  • getCellStyle(cell):获取图形的样式配置,其中shape属性是mxGraph内置的图形标识,常见值包括rectangle(矩形)、ellipse(椭圆)、triangle(三角形)、rhombus(菱形)等
  • 若需要统计更多图形类型,只需在shapeCounter中新增对应标识,并在结果组装部分添加对应的中文描述即可

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:50:15