效果
![](https://img2024.cnblogs.com/blog/724275/202404/724275-20240429002444608-480603176.png)
代码
<template>
<div class="app">
<div ref="myholder" id="paper"></div>
</div>
</template>
<script>
import * as joint from '@joint/core'
export default {
data() {
return {
graph: null,
}
},
mounted() {
const namespace = joint.shapes
var graph = new joint.dia.Graph({}, { cellNamespace: namespace })
this.graph = graph
var paper = new joint.dia.Paper({
el: this.$refs.myholder,
model: this.graph,
width: 600,
height: 300,
cellViewNamespace: namespace,
drawGrid: true,
gridSize: 10,
background: {
color: 'rgba(0, 255, 0, 0.3)',
},
})
const node1 = this.drawRect({ x: 100, y: 30 }, 'Hello')
const node2 = this.drawRect({ x: 300, y: 30 }, 'World!')
// const node3 = this.drawRect({ x: 250, y: 100 }, '哈哈哈')
this.drawLine(node1, node2)
// this.drawLine(node1, node3)
},
methods: {
drawRect({ x, y }, text) {
var rect = new joint.shapes.standard.Rectangle()
rect.position(x, y)
rect.resize(100, 40)
rect.attr({
body: {
fill: '#2c3e50',
},
label: {
text,
fill: '#3498DB',
fontSize: 18,
fontWeight: 'bold',
fontVariant: 'Microsoft YaHei',
},
})
rect.addTo(this.graph)
return rect
},
drawLine(node1, node2) {
var link = new joint.shapes.standard.Link()
link.source(node1)
link.target(node2)
link.addTo(this.graph)
// 设置线条样式
// 方式1:
// link.attr('line/stroke', 'orange')
// 方式2
// link.attr({
// line: {
// stroke: 'red',
// },
// })
// 设置线条上的文本
// 方式1:
// link.labels([
// {
// attrs: {
// text: {
// text: '文本',
// },
// },
// },
// ])
// 方式2:
// link.appendLabel({
// attrs: {
// text: {
// text: '娃娃',
// },
// },
// })
// 设置连接线的起始和终点样式
// 下面使用路径表示箭头
// link.attr({
// line: {
// sourceMarker: {
// type: 'path',
// fill: 'red',
// d: 'M 20 -10 0 0 20 10 Z',
// },
// targetMarker: {
// type: 'path',
// stroke: 'green',
// 'stroke-width': 2,
// fill: 'yellow',
// d: 'M 20 -10 0 0 20 10 Z',
// },
// },
// })
// 设置链接顶点数组
link.vertices([
new joint.g.Point(250, 100),
new joint.g.Point(280, 100),
new joint.g.Point(300, 120),
])
link.router('orthogonal')
// link.connector('rounded')
link.attr({
line: {
stroke: 'gray',
// strokeWidth: 4,
// strokeDasharray: '4 2',
sourceMarker: {
type: 'image',
'xlink:href':
'https://cdn3.iconfinder.com/data/icons/49handdrawing/24x24/left.png',
width: 24,
height: 24,
y: -12,
},
targetMarker: {
type: 'image',
'xlink:href':
'https://cdn3.iconfinder.com/data/icons/49handdrawing/24x24/left.png',
width: 24,
height: 24,
y: -12,
},
},
})
},
},
}
</script>
<style lang="less" scoped>
#paper {
border: 1px solid;
}
</style>