<template>
  <div class='topology'>
    <canvas ref='canvas' />
  </div>
</template>
<script>
export default {
  data() {
    return {
      nodes: [
        { id: 1, name: 'Node 1', x: 100, y: 100 },
        { id: 2, name: 'Node 2', x: 200, y: 200 },
        { id: 3, name: 'Node 3', x: 300, y: 100 },
        { id: 4, name: 'Node 4', x: 400, y: 200 },
      ],
      links: [
        { source: 1, target: 2 },
        { source: 2, target: 3 },
        { source: 3, target: 4 },
        { source: 4, target: 1 },
      ],
    };
  },
  mounted() {
    this.draw();
  },
  methods: {
    draw() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制节点
      this.nodes.forEach((node) => {
        ctx.beginPath();
        ctx.arc(node.x, node.y, 20, 0, 2 * Math.PI);
        ctx.fillStyle = '#fff';
        ctx.fill();
        ctx.lineWidth = 2;
        ctx.strokeStyle = '#000';
        ctx.stroke();
        ctx.closePath();
        ctx.fillStyle = '#000';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(node.name, node.x, node.y - 25);
      });

      // 绘制连线
      this.links.forEach((link) => {
        const sourceNode = this.nodes.find((node) => node.id === link.source);
        const targetNode = this.nodes.find((node) => node.id === link.target);

        ctx.beginPath();
        ctx.moveTo(sourceNode.x, sourceNode.y);
        ctx.lineTo(targetNode.x, targetNode.y);
        ctx.lineWidth = 2;
        ctx.strokeStyle = '#000';
        ctx.stroke();
        ctx.closePath();
      });
    },
  },
};
</script>
<style scoped>
.topology {
  width: 500px;
  height: 500px;
}
</style>
<p>该示例代码中定义了一个包含节点和连线信息的 data 对象,节点和连线的绘制通过使用 Canvas API 来实现。mounted 钩子函数中调用了 draw 方法,在 draw 方法中进行拓扑图的绘制。绘制节点时,使用 Canvas API 绘制圆形,并在圆形中央绘制节点名称。绘制连线时,获取每个连线的源节点和目标节点,并使用 Canvas API 绘制直线连接两个节点。最后,将绘制的内容渲染到 Canvas 元素中,完成拓扑图的绘制。</p>
Vue.js 拓扑图绘制示例代码:使用 Canvas API 创建网络图

原文地址: https://www.cveoy.top/t/topic/nwGZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录