JS-SVG关系图
一、基础概念
二、相关优势
三、应用场景
四、遇到的问题及解决方法
五、示例代码
以下是一个简单的JS-SVG关系图示例,展示了如何使用JavaScript动态创建SVG元素并添加交互功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS-SVG关系图示例</title>
<style>
.node {
fill: #999;
stroke: #333;
stroke-width: 2;
cursor: pointer;
}
.link {
fill: none;
stroke: #666;
stroke-width: 2;
}
</style>
</head>
<body>
<svg id="graph" width="600" height="400"></svg>
<script>
const svg = document.getElementById('graph');
// 创建节点
function createNode(x, y, label) {
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('class', 'node');
circle.setAttribute('cx', x);
circle.setAttribute('cy', y);
circle.setAttribute('r', 20);
circle.addEventListener('click', () => alert(`节点${label}被点击`));
svg.appendChild(circle);
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', x);
text.setAttribute('y', y + 5);
text.textContent = label;
svg.appendChild(text);
}
// 创建连线
function createLink(x1, y1, x2, y2) {
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('class', 'link');
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
svg.appendChild(line);
}
// 创建一个简单的关系图
createNode(100, 100, 'A');
createNode(300, 100, 'B');
createNode(200, 300, 'C');
createLink(100, 100, 300, 100);
createLink(100, 100, 200, 300);
createLink(300, 100, 200, 300);
</script>
</body>
</html>
在这个示例中,我们定义了createNode
和createLink
函数来分别创建节点和连线。每个节点都是一个可点击的圆圈,点击时会弹出一个提示框显示节点的标签。