ChartGraphDynamic.vue 2.36 KB
Newer Older
hucy's avatar
hucy committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
<!--
 * 动态增加图节点
  -->
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption;
type ECharts = echarts.ECharts;

interface StateType {
  data: NonNullable<echarts.GraphSeriesOption['data']>;
  edges: NonNullable<echarts.GraphSeriesOption['edges']>;
  timer: null | NodeJS.Timeout;
}

defineExpose({
  reset,
});

const chartGraphDynamicRef = ref<any>(null);
const state = reactive<StateType>({
  data: [],
  edges: [],
  timer: null,
});
onMounted(() => {
  getChart();
});

var graphDynamicChart: ECharts;
function getChart() {
  if (graphDynamicChart != null && graphDynamicChart != undefined) {
    graphDynamicChart.dispose();
  }
  graphDynamicChart = echarts.init(chartGraphDynamicRef.value);
  let option: EChartsOption;

  state.data = [
    {
      fixed: true,
      x: graphDynamicChart.getWidth() / 2,
      y: graphDynamicChart.getHeight() / 2,
      symbolSize: 18,
      id: '0',
      name: '原点',
      itemStyle: {
        color: '#FEB139',
      },
    },
  ];
  state.edges = [];

  option = {
    series: [
      {
        type: 'graph',
        roam: true,
        layout: 'force',
        animation: false,
        data: state.data,
        force: {
          // initLayout: 'circular'
          // gravity: 0
          repulsion: 100,
          edgeLength: 5,
        },
        edges: state.edges,
      },
    ],
  };

  run();
  option && graphDynamicChart.setOption(option);
}

function run() {
  if (state.timer) {
    clearTimer();
  }
  state.timer = setInterval(function () {
    state.data.push({
      id: state.data.length + '',
      itemStyle: {
        color: '#8bc24c',
      },
    });
    let source = Math.round((state.data.length - 1) * Math.random());
    let target = Math.round((state.data.length - 1) * Math.random());

    // 把不相同的两点连接起来
    if (source !== target) {
      state.edges.push({
        source: source,
        target: target,
      });
    }
    graphDynamicChart.setOption({
      series: [
        {
          data: state.data,
          edges: state.edges,
        },
      ],
    });
  }, 1000);
}

function clearTimer() {
  clearInterval(Number(state.timer));
}

function reset() {
  getChart();
}
</script>
<template>
  <div class="fit" ref="chartGraphDynamicRef"></div>
</template>

<style lang="scss" scoped></style>