众所周知,x6只能在现有的节点之间连线,不能凭空连一条线出来,现在有需求需要实现拖拽划线的功能。
像这样:
实现思路
- 监听blank:mousedown事件,在鼠标点击时在当前点绘制直线,并且将终点存起来
- 监听blank:mousemove事件,在移动事件中移动终点
- 监听blank:mouseup事件,鼠标抬起时结束划线
代码
以下是用vue3+x6实现的代码,只写了ts的部分
<script lang="ts" setup>
// 起点和终点
const source = ref()
const target = ref()
// 画布实例
const { graph } = useGraph()
// 在当前点绘制直线
function AddLine(point: number[]) {
source.value = graph.addNode({
shape: 'circle',
x: point[0],
y: point[1],
width: 20,
height: 20,
})
target.value = graph.addNode({
shape: 'circle',
x: point[0],
y: point[1],
width: 20,
height: 20,
})
graph.addEdge({
source: source.value,
target: target.value,
zIndex: 0,
attrs: {
line: {
targetMarker: null, // 去掉箭头
},
},
})
}
const isDrawing = ref(false)
// 开始绘制边
function startDrawEdge() {
// 鼠标按下时,在当前点绘制直线,并开启绘制状态
graph.on('blank:mousedown', (e) => {
const { x, y } = e
AddLine([x, y])
isDrawing.value = true
})
// 鼠标移动时,移动终点
graph.on('blank:mousemove', (e) => {
if (isDrawing.value) {
const { x, y } = e
target.value.position(x, y)
}
})
// 鼠标抬起时,结束绘制状态
graph.on('blank:mouseup', (e) => {
isDrawing.value = false
})
}
// 停止绘制
function stopDrawEdge() {
graph.off('blank:mousedown')
graph.off('blank:mousemove')
graph.off('blank:mouseup')
}
onMounted(()=>{
startDrawEdge()
})
</script>