
这是从网上看到的一个示例,不过没有源码
想用antvx6实现这样一种效果,谁有类似的demo源码,谢谢
上午好☀️☀️☀️️
本答案参考通义千问
当然可以!你提到的 AntV X6 是一个强大的图编辑器库,而 Stencil 是用于创建图形拖拽面板的组件。虽然官方示例能够实现基本功能,但确实存在样式不够美观、布局不灵活的问题,特别是在控件较多时。
你提到的“拖拽demo”如果是指我之前展示过的示例,那么它通常使用了更现代的前端框架(如 React)结合 AntV X6 实现了一个更友好的 UI 界面,包括可拖拽的节点和美观的工具栏。
你希望:
以下是完整的解决方案,包括 HTML + JavaScript + CSS 示例,你可以直接复制运行测试。
├── index.html
├── style.css
└── script.js
index.html)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>AntV X6 拖拽 Demo</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<!-- 工具栏 -->
<div id="toolbar">
<h3>节点库</h3>
<div id="stencil"></div>
</div>
<!-- 图形容器 -->
<div id="graph"></div>
</div>
<!-- 引入 AntV X6 -->
<script src="https://unpkg.com/@antv/x6@4.5.0/dist/x6.min.js"></script>
<script src="script.js"></script>
</body>
</html>
style.css)body {
margin: 0;
font-family: Arial, sans-serif;
}
#container {
display: flex;
height: 100vh;
}
#toolbar {
width: 200px;
background-color: #f5f5f5;
padding: 10px;
box-sizing: border-box;
}
#stencil {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 10px;
}
.node-icon {
width: 40px;
height: 40px;
background-color: #409EFF;
color: white;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: transform 0.2s;
}
.node-icon:hover {
transform: scale(1.1);
}
script.js)const { Graph, Shape, Stencil } = window.X6;
// 创建画布
const graph = new Graph({
container: 'graph',
width: window.innerWidth - 200,
height: window.innerHeight,
fitView: true,
});
// 创建工具栏
const stencil = new Stencil({
target: graph,
width: 180,
height: 300,
items: [
{
id: 'rect',
label: '矩形',
shape: 'rect',
size: [80, 40],
attrs: {
body: {
fill: '#409EFF',
stroke: '#333',
},
},
},
{
id: 'circle',
label: '圆形',
shape: 'circle',
size: [60, 60],
attrs: {
body: {
fill: '#FFA500',
stroke: '#333',
},
},
},
{
id: 'ellipse',
label: '椭圆',
shape: 'ellipse',
size: [80, 40],
attrs: {
body: {
fill: '#7CFC00',
stroke: '#333',
},
},
},
],
});
// 将工具栏添加到 DOM 中
stencil.render(document.getElementById('stencil'));
// 鼠标点击事件绑定(可选)
document.getElementById('stencil').addEventListener('click', (e) => {
if (e.target.classList.contains('node-icon')) {
const type = e.target.dataset.type;
const node = graph.addNode({
x: 100,
y: 100,
shape: type,
size: [80, 40],
});
}
});
Stencil 样式;node-icon 类统一控制图标样式。Stencil 绑定图形元素;items 数组管理节点类型;| 项目 | 内容 |
|------|------|
| 工具栏 | 使用 CSS Grid 实现自定义布局 |
| 节点拖拽 | 通过 Stencil 实现拖拽创建 |
| 扩展性 | 易于添加新图形类型 |
| 美观度 | 提升了整体视觉体验 |
如果你希望将这个示例集成到 React/Vue/TypeScript 等项目中,也可以告诉我,我可以为你提供对应版本的源码。
需要我帮你封装成 React 组件吗?