欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue使用GraphVis开发无限拓展的关系图谱的实现

程序员文章站 2022-06-22 09:46:26
1、去graphvis官网下载对应的js,新版和旧版的js有所不同,看自己需求引入旧版还是新版(graphvis官方网址:) visgraph.min.js (基本配置js) visgra...

1、去graphvis官网下载对应的js,新版和旧版的js有所不同,看自己需求引入旧版还是新版(graphvis官方网址:)

  • visgraph.min.js (基本配置js)
  • visgraph-layout.min.js(配置布局js)

2、在需要的vue文件引入js文件

import visgraph from '@/assets/js/graphvis/old/visgraph.min.js' // 自己对应的js文件位置
import layoutfactory from '@/assets/js/graphvis/old/visgraph-layout.min.js' // 自己对应的js文件位置
export default { components: { visgraph, layoutfactory } }

3、加载画布和配置

配置(自己根据需求修改配置):

config: {
  // 节点配置
          node: {
            label: { // 标签配置
              show: true, // 是否显示
              color: '250,250,250', // 字体颜色
              font: 'normal 14px microsoft yahei', // 字体大小及类型
              textposition: 'middle_center', // 字体位置
              wraptext: true // 节点包裹文字(该属性为true时只对于字体位置为middle_center时有效)
            },
            shape: 'circle', // 节点形状 circle,rect,square,ellipse,triangle,star,polygon,text
            // width: 60, // 节点宽度(只对于shape为rect时有效)
            // height: 60, // 节点高度(只对于shape为rect时有效)
            color: '62,160,250', // 节点颜色
            bordercolor: '62,160,250', // 节点边框颜色
            borderwidth: 0, // 节点边框宽度
            borderradius: 0, // 节点圆角
            linedash: [0], // 节点边框线条类型 [0] 表示实线 [5,8] 表示虚线 borderwidth > 0有效
            alpha: 1, // 节点透明度
            size: 60, // 节点大小
            selected: { // 节点选中后样式
              bordercolor: '136,198,255', // 选中时边框颜色
              borderalpha: 1, // 选中时的边框透明
              borderwidth: 3, // 选中是的边框宽度
              showshadow: true, // 是否展示阴影
              shadowcolor: '136,198,255' // 选中是的阴影颜色
            }
          },
          // 线条配置
          link: {
            label: { // 标签配置
              show: true, // 是否显示
              color: '100,100,200', // 标签颜色
              font: 'normal 10px arial' // 标签文字大小及类型
            },
            linetype: 'direct', // 线条类型direct,curver,vlink,hlink,bezier,vbezier,hbezier
            colortype: 'defined', // 连线颜色类型 source:继承source颜色,target:继承target颜色 both:用双边颜色,defined:自定义
            color: '200,200,200', // 线条颜色
            alpha: 1, // 连线透明度
            linewidth: 1, // 连线宽度
            linedash: [0], // 虚线间隔样式如:[5,8]
            showarrow: true, // 显示箭头
            selected: { // 选中时的样式设置
              color: '20,250,50', // 选中时的颜色
              alpha: 1, // 选中时的透明度
              linewidth: 4, // 选中线条宽度
              showshadow: true, // 显示阴影
              shadowcolor: '50,250,50' // 阴影颜色
            }
          },
          highlightneiber: true, // 相邻节点高度标志
          wheelzoom: 0.8 // 滚轮缩放开关,不使用时不设置[0,1]  
}

加载画布:

this.visgraph = new visgraph(
        document.getelementbyid(this.canvasid),
        this.canvasconfig
      )
this.visgraph.clearall()
this.visgraph.drawdata(this.graphdata)

4、拓展功能:

  无限拓展子节点,双击节点触发(ondblclick): 

this.visgraph.restorehightlight() // 取消高亮
const allnodes = this.visgraph.getvisibledata()
this.currentnode.push(node.id)
allnodes.nodes.foreach(item => {
    if (this.currentnode.indexof(item.id) === (-1)) {
         this.visgraph.deletenode(item)
    }
})
const findnodenum = math.round(math.random() * 50)
const increamdata = this.buildincreamdata(node, findnodenum)
this.visgraph.activeaddnodelinks(increamdata.nodes, increamdata.links)
this.visgraph.translatetocenter()

完整代码(relation.vue):

<!--
 * @author: carlyang
 * @date: 2021-07-23 15:31:51
 * @lastedittime: 2021-07-30 09:46:05
 * @lasteditors: please set lasteditors
 * @description: 关系图谱
 * @filepath: \vue-g6\src\views\graphvis\company.vue
-->
<template>
  <div id="container">
    <!-- ============================================= 画布视图 ============================================= -->
    <div
      id="graph-panel"
      ref="graphpanel"
      @contextmenu="globalclickeddispatch"
    ></div>

    <!-- ============================================= 左侧工具栏 ============================================= -->
    <div class="left-toolbar">
      <ul>
        <li @click="setzoomout" title="放大">
          <i class="iconfont icon-zoomin"></i>
        </li>
        <li @click="setzoomin" title="缩小">
          <i class="iconfont icon-zoomout"></i>
        </li>
        <li @click="saveimage" title="保存图片">
          <i class="iconfont icon-baocun-"></i>
        </li>
        <li @click="exportjson" title="导出json">
          <i class="iconfont icon-json"></i>
        </li>
        <li @click="showoverview" title="缩略图">
          <i class="iconfont icon-suolvetu" style="font-size: 14px"></i>
        </li>
        <li @click="clockwiserotate" title="顺时针旋转">
          <i class="iconfont icon-shunshizhenfangxiangclockwise4" style="font-size: 14px"></i>
        </li>
        <li @click="counterclockwiserotate" title="逆时针旋转">
          <i class="iconfont icon-nishizhencounterclockwise3" style="font-size: 14px"></i>
        </li>
        <li @click="setmousemodel('normal')" title="正常模式">
          <i class="iconfont icon-pointer-up"></i>
        </li>
        <li @click="setmousemodel('drag')" title="拖拽模式">
          <i class="iconfont icon-line-dragmovetuozhuai-01"></i>
        </li>
        <li @click="setmousemodel('select')" title="框选模式">
          <i class="iconfont icon-kuangxuan1"></i>
        </li>
        <li @click="fullscreen" title="全屏显示">
          <i class="iconfont icon-quanping" style="font-size: 20px"></i>
        </li>
      </ul>
    </div>

    <!-- ============================================= 右键菜单 ============================================= -->
    <div id="nodemenudialog" class="nodemenudialog">
      <ul>
        <li @click="clicknodeinfo">节点信息</li>
        <li @click="settingnode">配置节点</li>
        <li @click="selectrelation">选中关联</li>
        <li @click="deletenode">删除节点</li>
        <li @click="contractnode">收起节点</li>
        <li @click="expandednode">展开节点</li>
      </ul>
    </div>

    <!-- ============================================= 节点信息弹框 ============================================= -->
    <el-drawer
      title="节点信息"
      :visible.sync="nodeinfodrawer"
      direction="rtl"
      :modal="false"
      size="20%"
    >
      <div class="nodeinfo">
        <el-form class="nodeinfoform" ref="nodeinfoform" :model="nodeinfoform" label-width="80px">
          <el-form-item label="节点名称">
            <el-input v-model="nodeinfoform.label"></el-input>
          </el-form-item>
          <el-form-item label="节点id">
            <el-input v-model="nodeinfoform.id"></el-input>
          </el-form-item>
        </el-form>
        <el-tabs v-model="nodeinfoactivename" :stretch="true" class="nodeinfotabs">
          <el-tab-pane label="关联关系" name="first">
            <div class="nodeinforelation">
              <el-collapse v-model="nodeinforelationactive">
                <el-collapse-item title="目标节点" name="1">
                  <template slot="title">
                    <el-badge :value="nodeinfosourcelist.length">目标节点</el-badge>
                  </template>
                  <table
                    border="0"
                    cellspacing="0"
                    cellpadding="0"
                    class="nodeinfo-table"
                    v-if="nodeinfosourcelist.length > 0"
                  >
                    <thead>
                      <tr>
                        <th>实体对象</th>
                        <th>关系类型</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, index) in nodeinfosourcelist" :key="index">
                        <td
                          :style="{ color: item.color }"
                          style="cursor: pointer;"
                          @click="movecenterthisnode(item.id)"
                        >{{ item.label }}</td>
                        <td>{{ item.relationtype }}</td>
                      </tr>
                    </tbody>
                  </table>
                  <p v-else>无数据</p>
                </el-collapse-item>
                <el-collapse-item title="来源节点" name="2">
                  <template slot="title">
                    <el-badge :value="nodeinfotargetlist.length">来源节点</el-badge>
                  </template>
                  <table
                    border="0"
                    cellspacing="0"
                    cellpadding="0"
                    class="nodeinfo-table"
                    v-if="nodeinfotargetlist.length > 0"
                  >
                    <thead>
                      <tr>
                        <th>实体对象</th>
                        <th>关系类型</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, index) in nodeinfotargetlist" :key="index">
                        <td
                          :style="{ color: item.color }"
                          style="cursor: pointer;"
                          @click="movecenterthisnode(item.id)"
                        >{{ item.label }}</td>
                        <td>{{ item.relationtype }}</td>
                      </tr>
                    </tbody>
                  </table>
                  <p v-else>无数据</p>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-tab-pane>
          <el-tab-pane label="属性" name="second">
            <div class="nodeinfoattribute">
              <el-table :data="nodeinfoattributelist" border style="width: 100%">
                <el-table-column prop="name" label="属性名"></el-table-column>
                <el-table-column prop="value" label="属性值"></el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <!-- ============================================= 节点配置 ============================================= -->
    <el-drawer
      title="节点配置"
      :visible.sync="nodeconfigdrawer"
      direction="rtl"
      :modal="false"
      size="20%"
    >
      <div class="nodeconfig">
        <el-form ref="form" :model="nodeconfigform" label-width="80px" label-position="left">
          <el-form-item label="名称">
            <el-input v-model="nodeconfigform.label" placeholder="请输入节点名称"></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="nodeconfigform.shape" placeholder="请选择节点类型">
              <el-option
                v-for="(item, index) in nodetypelist"
                :key="'node' + index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="颜色">
            <div class="form-color">
              <el-input
                v-model="nodeconfigform.fillcolor"
                class="form-input"
                placeholder="请选择颜色"
                readonly
              ></el-input>
              <el-color-picker
                v-model="nodeconfigform.hexcolor"
                class="form-color-select"
                @change="colorchange(nodeconfigform.hexcolor, 'fillcolor')"
              ></el-color-picker>
            </div>
          </el-form-item>
          <el-form-item label="大小">
            <el-input v-model="nodeconfigform.size" placeholder="请输入节点大小" type="number"></el-input>
          </el-form-item>
          <el-form-item label="边框宽度">
            <el-input v-model="nodeconfigform.borderwidth" placeholder="请输入边框宽度" type="number"></el-input>
          </el-form-item>
          <el-form-item label="边框虚线">
            <el-select v-model="nodeconfigform.borderdash" placeholder="请选择边框虚线">
              <el-option label="否" :value="false"></el-option>
              <el-option label="是" :value="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="边框颜色">
            <div class="form-color">
              <el-input
                v-model="nodeconfigform.bordercolor"
                class="form-input"
                placeholder="请选择边框颜色"
                readonly
              ></el-input>
              <el-color-picker
                v-model="nodeconfigform.borderhexcolor"
                class="form-color-select"
                @change="colorchange(nodeconfigform.borderhexcolor, 'bordercolor')"
              ></el-color-picker>
            </div>
          </el-form-item>
          <el-form-item label="字体位置">
            <el-select v-model="nodeconfigform.textposition" placeholder="请选择字体位置">
              <el-option
                v-for="(item, index) in textpositionlist"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="字体样式">
            <el-input v-model="nodeconfigform.font" placeholder="请输入字体样式"></el-input>
          </el-form-item>
          <el-form-item label="字体颜色">
            <div class="form-color">
              <el-input
                v-model="nodeconfigform.fontcolor"
                class="form-input"
                placeholder="请选择字体颜色"
                readonly
              ></el-input>
              <el-color-picker
                v-model="nodeconfigform.fonthexcolor"
                class="form-color-select"
                @change="colorchange(nodeconfigform.fonthexcolor, 'fontcolor')"
              ></el-color-picker>
            </div>
          </el-form-item>
          <el-form-item label="字体背景">
            <div class="form-color">
              <el-input
                v-model="nodeconfigform.fontbgcolor"
                class="form-input"
                placeholder="请选择字体背景"
                readonly
              ></el-input>
              <el-color-picker
                v-model="nodeconfigform.fontbghexcolor"
                class="form-color-select"
                @change="colorchange(nodeconfigform.fontbghexcolor, 'fontbgcolor')"
              ></el-color-picker>
            </div>
          </el-form-item>
          <el-form-item label="字体偏移">
            <el-input
              v-model="nodeconfigform.textoffset"
              placeholder="请输入字体偏移"
              type="number"
              max="100"
              min="-100"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="save-setting">
          <el-button type="primary" @click="savesetting">保存配置</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import visgraph from '@/assets/js/graphvis/old/visgraph.min.js'
import layoutfactory from '@/assets/js/graphvis/old/visgraph-layout.min.js'
import screenfull from 'screenfull'
import {
  company
} from '@/assets/js/company.js'
export default {
  name: 'designgraph',
  components: {
    visgraph,
    layoutfactory
  },
  data() {
    return {
      // 画布实例
      visgraph: null,
      // 中心节点
      centernode: null,
      // 已选中节点
      currentnode: [],
      // 选中节点信息
      checkednodeinfo: {},
      // 图谱配置
      config: {
        node: {
          label: {
            show: true,
            color: '250,250,250',
            font: 'normal 14px microsoft yahei',
            textposition: 'middle_center',
            borderwidth: 0,
            wraptext: true
          },
          shape: 'circle',
          width: 60,
          height: 60,
          color: '62,160,250',
          bordercolor: '62,160,250',
          borderwidth: 0,
          borderradius: 0,
          linedash: [0],
          alpha: 1,
          selected: {
            bordercolor: '136,198,255',
            borderalpha: 1,
            borderwidth: 3,
            showshadow: true,
            shadowcolor: '136,198,255'
          },
          onclick: (event, node) => {
            // this.visgraph.highlightneibernodes(node, 1) // 高亮
          },
          ondblclick: (event, node) => {
            this.visgraph.restorehightlight() // 取消高亮
            const allnodes = this.visgraph.getvisibledata()
            this.currentnode.push(node.id)
            allnodes.nodes.foreach(item => {
              if (this.currentnode.indexof(item.id) === (-1)) {
                this.visgraph.deletenode(item)
              }
            })
            const findnodenum = math.round(math.random() * 50)
            const increamdata = this.buildincreamdata(node, findnodenum)
            this.visgraph.activeaddnodelinks(increamdata.nodes, increamdata.links)
            this.visgraph.translatetocenter()
          },
          onmouseover: (event, node) => { },
          onmouseout: (event, node) => { }
        },
        link: {
          label: {
            show: true,
            color: '100,100,200',
            font: 'normal 10px arial'
          },
          linetype: 'direct',
          colortype: 'defined',
          color: '200,200,200',
          alpha: 1,
          linewidth: 1,
          linedash: [0],
          showarrow: true,
          selected: {
            color: '20,250,50',
            alpha: 1,
            linewidth: 4,
            showshadow: true,
            shadowcolor: '50,250,50'
          }
        },
        highlightneiber: true,
        wheelzoom: 0.8,
        noelementclick: (event, _graphvis) => {
          // 点击画布其他位置,弹框隐藏
          this.nodemenudialogclose()
        }
      },
      // 节点信息弹框
      nodeinfodrawer: false,
      // 节点信息表单
      nodeinfoform: {
        label: '',
        id: ''
      },
      // 节点信息弹框tab选项名称
      nodeinfoactivename: 'first',
      // 关联关系
      nodeinforelationactive: ['1', '2'],
      // 目标节点列表
      nodeinfotargetlist: [],
      // 来源节点列表
      nodeinfosourcelist: [],
      // 节点属性列表
      nodeinfoattributelist: [],
      // 节点配置弹框
      nodeconfigdrawer: false,
      // 节点配置表单
      nodeconfigform: {
        label: '',
        shape: '',
        fillcolor: '',
        hexcolor: '',
        size: '',
        borderwidth: '',
        borderdash: '',
        bordercolor: '',
        borderhexcolor: '',
        textposition: '',
        font: '',
        fontcolor: '',
        fonthexcolor: '',
        fontbgcolor: '',
        fontbghexcolor: '',
        textoffset: ''
      },
      // 节点类型列表
      nodetypelist: [
        { value: 'circle', label: '圆形' },
        { value: 'rect', label: '矩形' },
        { value: 'ellipse', label: '椭圆形' },
        { value: 'star', label: '五角形' },
        { value: 'triangle', label: '三角形' },
        { value: 'polygon', label: '六边形' }
      ],
      // 字体位置列表
      textpositionlist: [
        { value: 'middle_center', label: '居中' },
        { value: 'bottom_center', label: '底部' },
        { value: 'top_center', label: '顶部' },
        { value: 'middle_left', label: '左方' },
        { value: 'middle_right', label: '右方' },
      ]
    }
  },
  mounted() {
    this.handledata(company)
    window.onresize = () => {
      if (this.visgraph) {
        this.visgraph.movecenter()
      }
    }
  },
  methods: {
    /**
     * 处理数据
     * @date 2021-07-23
     * @param {object} data
     */
    handledata(data) {
      const obj = {
        nodes: [],
        links: []
      }
      const nodes = data.nodes
      nodes.foreach(item => {
        if (item.label === '总公司') {
          const nodeobj = {
            id: item.id,
            label: item.label,
            properties: item,
            color: '38,186,191',
            selectedbordercolor: '131,218,228',
            shadowcolor: '131,218,228'
          }
          nodeobj.size = 80
          nodeobj.x = 250
          nodeobj.y = 250
          this.centernode = nodeobj
          this.currentnode.push(item.id)
        } else {
          const nodeobj = {
            id: item.id,
            label: item.label,
            properties: item,
            size: 60
          }
          switch (item.type) {
            case 1:
              nodeobj.color = '242,105,97'
              nodeobj.selectedbordercolor = '249,179,157'
              nodeobj.shadowcolor = '249,179,157'
              break
          }
          obj.nodes.push(nodeobj)
        }
      })
      const links = data.edges
      links.foreach(item => {
        const linkobj = {
          id: item.id,
          target: item.to,
          source: item.from,
          label: item.label,
          properties: item
          // strokecolor: this.getrandomcolor()
        }
        switch (item.type) {
          case 11:
            linkobj.color = '40,194,199'
            linkobj.selectedcolor = '40,194,199'
            linkobj.shadowcolor = '40,194,199'
            break
          case 12:
            linkobj.color = '250,108,100'
            linkobj.selectedcolor = '250,108,100'
            linkobj.shadowcolor = '250,108,100'
            break
          case 13:
            linkobj.color = '0,132,255'
            linkobj.selectedcolor = '0,132,255'
            linkobj.shadowcolor = '0,132,255'
            break
          case 15:
            linkobj.color = '250,108,100'
            linkobj.selectedcolor = '250,108,100'
            linkobj.shadowcolor = '250,108,100'
            break
        }
        obj.links.push(linkobj)
      })
      this.builddata(obj)
    },
    /**
     * 搭建实例
     * @date 2021-07-23
     * @param {object} gxdata
     */
    builddata(gxdata) {
      this.visgraph = new visgraph(document.getelementbyid('graph-panel'), this.config)
      const nodecount = gxdata.nodes.length
      const xyarr = this.getxy(this.centernode, nodecount, nodecount * 20)
      gxdata.nodes.foreach((n, i) => {
        n.x = xyarr[i].x
        n.y = xyarr[i].y
        n.size = 60
      })
      gxdata.nodes.push(this.centernode)
      this.visgraph.drawdata(gxdata)
      this.visgraph.setzoom()
    },
    /**
     * 遍布选中节点周围的点坐标
     * @date 2021-07-23
     * @param {中心节点} centernode
     * @param {节点数量} nodecount
     * @param {距离中心点距离} raduis
     * @returns {array}
     */
    getxy(centernode, nodecount, raduis) {
      const aop = 360.0 / nodecount
      const arr = []
      for (let i = 0; i < nodecount; i++) {
        let r1 = raduis
        if (nodecount > 10) {
          r1 = (i % 2 === 0 ? raduis + 35 : raduis - 35)
        }
        const ao = i * aop
        const o1 = {}
        o1.x = centernode.x + r1 * math.cos(ao * math.pi / 180)
        o1.y = centernode.y + r1 * math.sin(ao * math.pi / 180)
        arr[i] = o1
      }
      return arr
    },
    /**
     * 随机产生节点
     * @date 2021-07-23
     * @param {当前选中节点} centernode
     * @param {节点数量} nodenum
     * @returns {object}
     */
    buildincreamdata(centernode, nodenum) {
      const gxdata = {
        nodes: [],
        links: []
      }
      const count = nodenum
      const nodeidprefix = 'node_' + math.round(math.random() * 1000) + '_'
      for (let i = 0; i < count; i++) {
        gxdata.nodes.push({
          id: nodeidprefix + i,
          label: '子节点+' + i,
          size: 60
          // color: this.getrandomcolor()
        })
        gxdata.links.push({
          source: centernode.id,
          target: nodeidprefix + i,
          label: '关系' + i
        })
      }
      return gxdata
    },
    /**
     * 画布右键事件
     * @date 2021-07-26
     * @param {object} event
     */
    globalclickeddispatch(event) {
      if (event.button === 2) {
        if (this.visgraph.currentnode) {
          this.nodemenudialogopen(event, this.visgraph.currentnode)
        }
      }
    },
    /**
     * 右键节点菜单显示
     * @date 2021-07-26
     * @param {object} event
     * @param {object} node
     */
    nodemenudialogopen(event, node) {
      let nodemenudialog = document.getelementbyid("nodemenudialog");
      nodemenudialog.style.left = event.clientx + "px";
      nodemenudialog.style.top = (event.clienty - 76) + "px";
      nodemenudialog.style.display = "block";
      this.checkednodeinfo = node;
      event.stoppropagation();
    },
    /**
     * 关闭节点菜单
     * @date 2021-07-26
     */
    nodemenudialogclose() {
      let nodemenudialog = document.getelementbyid("nodemenudialog");
      nodemenudialog.style.display = "none";
    },
    /**
     * 点击节点信息
     * @date 2021-07-26
     */
    clicknodeinfo() {
      this.nodeinfodrawer = true
      // 赋值表单
      this.nodeinfoform = this.checkednodeinfo
      // 关联节点
      // 出节点
      const k = this.checkednodeinfo
      const g = (k.outlinks || []).map((link) => {
        return {
          id: link.target.id,
          label: link.target.label,
          type: link.target.type,
          color: 'rgb(' + link.target.fillcolor + ')',
          relationtype: link.type || link.label || '--'
        }
      })
      // 入节点
      const h = (k.inlinks || []).map((link) => {
        return {
          id: link.source.id,
          label: link.source.label,
          type: link.source.type,
          color: 'rgb(' + link.source.fillcolor + ')',
          relationtype: link.type || link.label || '--'
        }
      })
      this.nodeinfotargetlist = h
      this.nodeinfosourcelist = g
      // 属性赋值
      const list = []
      const namelist = ['id', 'label', 'type', 'cluster', 'fillcolor', 'shape', 'size', 'font', 'fontcolor', 'x', 'y']
      namelist.foreach(item => {
        const obj = {
          name: item,
          value: this.checkednodeinfo[item]
        }
        list.push(obj)
      })
      this.nodeinfoattributelist = list
      this.nodemenudialogclose()
    },
    /**
     * 选中关联操作
     * @date 2021-07-26
     */
    selectrelation() {
      this.visgraph.rightmenuoprate('selrelate')
    },
    /**
     * 删除指定节点
     * @date 2021-07-26
     * @returns {any}
     */
    deletenode() {
      this.visgraph.deletenode(this.visgraph.currentnode)
      this.nodemenudialogclose()
    },
    /**
     * 收起指定节点
     * @date 2021-07-26
     * @returns {any}
     */
    contractnode() {
      if (this.visgraph.currentnode.outlinks.length > 0) {
        this.visgraph.contract(this.visgraph.currentnode)
        this.nodemenudialogclose()
      } else {
        this.$message.warning('当前节点无子节点,无法收起')
      }
    },
    /**
     * 展开指定节点
     * @date 2021-07-26
     * @returns {any}
     */
    expandednode() {
      if (this.visgraph.currentnode.outlinks.length > 0) {
        this.visgraph.expanded(this.visgraph.currentnode)
        this.nodemenudialogclose()
      } else {
        this.$message.warning('当前节点无子节点,无法展开')
      }
    },
    /**
     * 以指定节点为中心移动
     * @date 2021-07-26
     * @param {string} id
     */
    movecenterthisnode(id) {
      const node = this.visgraph.findnodebyid(id)
      this.visgraph.movenodetocenter(node)
    },
    /**
     * 节点配置
     * @date 2021-07-30
     * @returns {any}
     */
    settingnode () {
      this.nodemenudialogclose()
      const {
        id,
        label,
        shape,
        fillcolor,
        size,
        borderwidth,
        linedash,
        bordercolor,
        textposition,
        font,
        fontcolor,
        labelbackground,
        textoffsetx
      } = this.visgraph.currentnode
      this.nodeconfigform.id = id
      this.nodeconfigform.label = label
      this.nodeconfigform.shape = shape
      this.nodeconfigform.fillcolor = 'rgb(' + fillcolor + ')'
      this.nodeconfigform.hexcolor = this.rgbtohex('rgb(' + fillcolor + ')')
      this.nodeconfigform.size = size
      this.nodeconfigform.borderwidth = borderwidth
      this.nodeconfigform.borderdash = linedash.length === 2
      this.nodeconfigform.bordercolor = 'rgb(' + bordercolor + ')'
      this.nodeconfigform.borderhexcolor = this.rgbtohex('rgb(' + bordercolor + ')')
      this.nodeconfigform.textposition = textposition
      this.nodeconfigform.font = font
      this.nodeconfigform.fontcolor = 'rgb(' + fontcolor + ')'
      this.nodeconfigform.fonthexcolor = this.rgbtohex('rgb(' + fontcolor + ')')
      this.nodeconfigform.fontbgcolor = labelbackground ? 'rgb(' + labelbackground + ')' : ''
      this.nodeconfigform.fontbghexcolor = labelbackground ? this.rgbtohex('rgb(' + labelbackground + ')') : ''
      this.nodeconfigform.textoffset = textoffsetx
      this.nodeconfigdrawer = true
    },
    /**
     * 保存节点配置
     * @date 2021-07-30
     * @returns {any}
     */
    savesetting () {
      const {
        id,
        label,
        shape,
        fillcolor,
        hexcolor,
        size,
        borderwidth,
        borderdash,
        bordercolor,
        borderhexcolor,
        textposition,
        font,
        fontcolor,
        fonthexcolor,
        fontbgcolor,
        fontbghexcolor,
        textoffset
      } = this.nodeconfigform
      const b = this.visgraph.findnodebyattr('id', id)
      if (b) {
        b.label = label
        b.size = size
        b.shape = shape
        b.fillcolor = this.getcolorrgb(fillcolor)
        b.textposition = textposition
        b.fontcolor = this.getcolorrgb(fontcolor)
        b.labelbackground = this.getcolorrgb(fontbgcolor)
        b.font = font;
        b.textoffsety = number(textoffset) || 2
        b.borderwidth = number(borderwidth) || 2
        b.bordercolor = this.getcolorrgb(bordercolor)
        b.linedash = (borderdash ? [8, 5] : [0])
        this.visgraph.refresh()
        this.$message({
          message: '修改配置成功!',
          type: 'success',
          duration: 2000
        })
        this.nodeconfigdrawer = false
      } else {
        this.$message({
          message: '无法找到选中节点!',
          type: 'error',
          duration: 2000
        })
      }
    },
    /**
     * 随机获取颜色
     * @date 2021-07-20
     * @returns {string} 样式
     */
    getrandomcolor() {
      const r = math.floor(math.random() * 256)
      const g = math.floor(math.random() * 256)
      const b = math.floor(math.random() * 256)
      return 'rgb(' + r + ',' + g + ',' + b + ')'
    },
    /**
     * 颜色选择框变化赋值
     * @date 2021-07-26
     * @param {string} val
     * @param {string} kay
     */
    colorchange(val, key) {
      this.nodeconfigform[key] = this.hextorgba(val)
    },
    /**
     * 16进制色值转rgb
     * @date 2021-07-26
     * @param {string} hex
     * @returns {string}
     */
    hextorgba(hex) {
      return "rgb(" + parseint("0x" + hex.slice(1, 3)) + "," + parseint("0x" + hex.slice(3, 5)) + "," + parseint("0x" + hex.slice(5, 7)) + ")"
    },
    /**
     * rgb色值转16进制
     * @date 2021-07-26
     * @param {string} color
     * @returns {string}
     */
    rgbtohex(color) {
      const rgb = color.split(',');
      const r = parseint(rgb[0].split('(')[1]);
      const g = parseint(rgb[1]);
      const b = parseint(rgb[2].split(')')[0]);
      const hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).tostring(16).slice(1);
      return hex;
    },
    /**
     * 去掉rgb
     * @date 2021-07-30
     * @param {string} a
     * @returns {string}
     */
    getcolorrgb (a) {
      if (a && a.length > 0) {
        a = a.replace('rgb(', '').replace(')', '')
      } else {
        a = null
      }
      return a
    },
    /**
     * 保存图片
     * @date 2021-07-23
     */
    saveimage() {
      this.visgraph.saveimage()
    },
    /**
     * 导出json
     * @date 2021-07-30
     */
    exportjson () {
      this.visgraph.exportjsonfile()
    },
    /**
     * 打开缩略图
     * @date 2021-07-23
     */
    showoverview() {
      console.log(this.showoverviewflag)
      this.showoverviewflag = !this.showoverviewflag
      this.visgraph.showoverview(this.showoverview)
    },
    /**
     * 缩小操作
     * @date 2021-07-23
     */
    setzoomin() {
      this.visgraph.setzoom('zoomin')
    },
    /**
     * 放大操作
     * @date 2021-07-23
     */
    setzoomout() {
      this.visgraph.setzoom('zoomout')
    },
    /**
     * 顺时针旋转
     * @date 2021-07-23
     */
    clockwiserotate() {
      this.visgraph.rotategraph(-10)
    },
    /**
     * 逆时针旋转
     * @date 2021-07-23
     */
    counterclockwiserotate() {
      this.visgraph.rotategraph(10)
    },
    /**
     * 设置鼠标模式
     * @date 2021-07-23
     * @param {string} type  drag:拖动模式  select:框选模式   normal:正常模式
     */
    setmousemodel(type) {
      this.visgraph.setmousemodel(type)
    },
    /**
     * 全屏显示
     * @date 2021-07-23
     */
    fullscreen() {
      screenfull.request(this.$refs.graphpanel)
    }
  }
}
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  position: relative;
  #graph-panel {
    width:100%;
    height:100%;
    background:#9dadc1;
    position: absolute;
    z-index: 1;
  }
  /* 测试菜单栏 */
  .left-toolbar {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1000;
    width: 45px;
    height: 100%;
    background-color: #fafafa;
    border-right: 1px solid #e5e2e2;
    ul {
      li {
        text-align: center;
        height: 35px;
        color: #066fba;
        line-height: 35px;
        cursor: pointer;
        padding: 0;
        i {
          font-size: 18px;
        }
        &:hover {
          background-color: #6ea36d;
          color: #fff;
        }
      }
    }
  }

  /* 右键弹框样式 */
  .nodemenudialog {
    display: none;
    position: absolute;
    min-width: 100px;
    padding: 2px 3px;
    margin: 0;
    border: 1px solid #e3e6eb;
    background: #f9f9f9;
    color: #333;
    z-index: 100;
    border-radius: 5px;
    box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.2);
    transform: translate(0, 15px) scale(0.95);
    transition: transform 0.1s ease-out, opacity 0.1s ease-out;
    overflow: hidden;
    cursor: pointer;
    li {
      display: block;
      position: relative;
      margin: 0;
      padding: 0 10px;
      border-radius: 5px;
      white-space: nowrap;
      line-height: 30px;
      text-align: center;
      &:hover {
        background-color: #c3e5fd;
      }
    }
  }

  /* 节点信息弹框 */
  .nodeinfo {
    .nodeinfoform {
      padding: 20px 20px 0 20px;
      border: solid 1px #dcdfe6;
      border-left: none;
      border-right: none;
      margin: 20px 0;
    }
    .nodeinforelation {
      padding: 0 20px;
      .nodeinfo-table {
        width: 100%;
        overflow-y: scroll;
        th {
          width: 50%;
          border: 1px solid #ebeef5;
          padding: 9px 0 9px 9px;
          text-align: left;
          &:first-child {
            border-right: none;
          }
        }
        td {
          width: 50%;
          border: 1px solid #ebeef5;
          border-top: none;
          padding: 9px 0 9px 9px;
          &:first-child {
            border-right: none;
          }
        }
      }
      /deep/ .el-badge__content.is-fixed {
        top: 24px;
        right: -7px;
      }
      p {
        text-align: center;
        padding: 20px 0;
      }
    }

    .nodeinfoattribute {
      padding: 0 20px;
    }
  }

  /* 节点配置弹框 */
  .nodeconfig {
    padding: 20px 20px 0 20px;
    border: solid 1px #dcdfe6;
    border-left: none;
    border-right: none;
    margin: 20px 0;
    .form-color {
      display: flex;
      justify-content: space-between;
      .form-input {
        width: calc(100% - 50px);
      }
    }
    .save-setting {
      width: 100%;
      margin-bottom: 20px;
      .el-button {
        width: 100%;
      }
    }
  }
}
</style>

注:引入两个js的文件eslint会报错,可以把这个文件忽略,不使用eslint的可以忽略。同时该项目还基于element-ui开发,引入screenfull全屏插件,还有阿里图标库图标,自己按需引入。

demo演示:

vue使用GraphVis开发无限拓展的关系图谱的实现

到此这篇关于vue使用graphvis开发无限拓展的关系图谱的实现的文章就介绍到这了,更多相关vue graphvis关系图谱内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!