当前位置:首页 > JavaScript

js实现网络图

2026-01-31 01:55:14JavaScript

使用 D3.js 绘制网络图

D3.js 是一个强大的 JavaScript 库,适合创建复杂的网络图。以下是一个简单的实现示例:

// 定义 SVG 尺寸
const width = 800;
const height = 600;

// 创建 SVG 元素
const svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height);

// 模拟数据
const data = {
  nodes: [
    { id: 1, name: "Node 1" },
    { id: 2, name: "Node 2" },
    { id: 3, name: "Node 3" }
  ],
  links: [
    { source: 1, target: 2 },
    { source: 2, target: 3 }
  ]
};

// 创建力导向布局
const simulation = d3.forceSimulation(data.nodes)
  .force("link", d3.forceLink(data.links).id(d => d.id))
  .force("charge", d3.forceManyBody().strength(-100))
  .force("center", d3.forceCenter(width / 2, height / 2));

// 绘制连线
const link = svg.append("g")
  .selectAll("line")
  .data(data.links)
  .enter().append("line")
  .attr("stroke", "#999");

// 绘制节点
const node = svg.append("g")
  .selectAll("circle")
  .data(data.nodes)
  .enter().append("circle")
  .attr("r", 10)
  .attr("fill", "#69b3a2");

// 更新位置
simulation.on("tick", () => {
  link
    .attr("x1", d => d.source.x)
    .attr("y1", d => d.source.y)
    .attr("x2", d => d.target.x)
    .attr("y2", d => d.target.y);

  node
    .attr("cx", d => d.x)
    .attr("cy", d => d.y);
});

使用 vis.js 创建交互式网络图

vis.js 提供了更简单的 API 来创建网络图:

// 准备数据
const nodes = new vis.DataSet([
  { id: 1, label: "Node 1" },
  { id: 2, label: "Node 2" },
  { id: 3, label: "Node 3" }
]);

const edges = new vis.DataSet([
  { from: 1, to: 2 },
  { from: 2, to: 3 }
]);

// 配置选项
const options = {
  nodes: {
    shape: "dot",
    size: 16
  },
  physics: {
    enabled: true
  }
};

// 创建网络图
const container = document.getElementById("network");
const data = { nodes, edges };
const network = new vis.Network(container, data, options);

使用 Cytoscape.js 实现专业网络图

Cytoscape.js 是专门为网络图设计的库:

// 初始化 Cytoscape
const cy = cytoscape({
  container: document.getElementById("cy"),
  elements: [
    { data: { id: "n1" } },
    { data: { id: "n2" } },
    { data: { id: "n3" } },
    { data: { source: "n1", target: "n2" } },
    { data: { source: "n2", target: "n3" } }
  ],
  style: [
    {
      selector: "node",
      style: {
        "background-color": "#666",
        "label": "data(id)"
      }
    },
    {
      selector: "edge",
      style: {
        "width": 3,
        "line-color": "#ccc"
      }
    }
  ],
  layout: {
    name: "cose",
    animate: true
  }
});

使用 Sigma.js 处理大规模网络

Sigma.js 适合渲染大规模网络图:

// 初始化 Sigma
const s = new sigma({
  renderer: {
    container: document.getElementById("sigma-container"),
    type: "canvas"
  },
  settings: {
    defaultNodeColor: "#ec5148"
  }
});

// 添加数据
s.graph.addNode({
  id: "n1",
  label: "Node 1",
  x: 0,
  y: 0,
  size: 1
});

s.graph.addNode({
  id: "n2",
  label: "Node 2",
  x: 1,
  y: 1,
  size: 1
});

s.graph.addEdge({
  id: "e1",
  source: "n1",
  target: "n2"
});

// 刷新渲染
s.refresh();

自定义 Canvas 实现简单网络图

对于简单需求,可以直接使用 Canvas API:

js实现网络图

const canvas = document.getElementById("network-canvas");
const ctx = canvas.getContext("2d");

// 节点数据
const nodes = [
  { x: 100, y: 100, r: 10, label: "A" },
  { x: 200, y: 150, r: 10, label: "B" },
  { x: 150, y: 250, r: 10, label: "C" }
];

// 连线数据
const links = [
  { from: 0, to: 1 },
  { from: 1, to: 2 }
];

// 绘制连线
ctx.strokeStyle = "#999";
links.forEach(link => {
  const from = nodes[link.from];
  const to = nodes[link.to];
  ctx.beginPath();
  ctx.moveTo(from.x, from.y);
  ctx.lineTo(to.x, to.y);
  ctx.stroke();
});

// 绘制节点
ctx.fillStyle = "#69b3a2";
nodes.forEach(node => {
  ctx.beginPath();
  ctx.arc(node.x, node.y, node.r, 0, Math.PI * 2);
  ctx.fill();

  // 绘制标签
  ctx.fillStyle = "#000";
  ctx.fillText(node.label, node.x + 15, node.y + 5);
});

以上方法涵盖了从简单到复杂的各种网络图实现方案,可根据项目需求选择合适的库和技术方案。

标签: 网络图js
分享给朋友:

相关文章

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…

js 实现文件上传

js 实现文件上传

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。以下是一个基础示例: <input ty…