计算连接线路径
动画.gif
- 定义
利用SVG <path>属性,绘制链接线路经
<path> 标签用来定义路径。
下面的命令可用于路径数据:
M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
C = curveto
S = smooth curveto
Q = quadratic Belzier curve
T = smooth quadratic Belzier curveto
A = elliptical Arc
Z = closepath
- 弧线绘制方式
export const computeLinePath = (start, end, lineOffsetY = 0) => {
// 弧线绘制方式
const x = Math.abs(start.x - end.x)
const y = Math.abs(start.y - end.y)
if (x === 0 || y === 0) {
return `
M ${start.x} ${start.y}
L ${end.x} ${end.y}
`
}
let dir
let p1
let p2
if (end.y < start.y) {
const offsetY = 100
const offsetX = 150
dir = end.x - start.x > 0 ? 1 : -1
p1 = `${start.x + dir * offsetX}, ${start.y + offsetY}`
p2 = `${end.x - dir * offsetX}, ${end.y - offsetY}`
return `
M ${start.x} ${start.y - lineOffsetY}
C ${p1} ${p2} ${end.x} ${end.y}
`
}
const OffsetXP1 = +(1 / 12 * x).toFixed(0)
const OffsetXP2 = +(11 / 12 * x).toFixed(0)
const offsetYP1 = +(1 / 3 * y).toFixed(0)
const offsetYP2 = +(2 / 3 * y).toFixed(0)
dir = start.x - end.x > 0 ? -1 : 1
p1 = `${start.x + dir * OffsetXP1}, ${start.y + offsetYP1}`
p2 = `${start.x + dir * OffsetXP2}, ${start.y + offsetYP2}`
return `
M ${start.x} ${start.y - lineOffsetY}
C ${p1} ${p2} ${end.x} ${end.y}
`
}
- 绘制箭头
export const computeTrianglePath = (start, width) => {
return `
M ${start.x} ${start.y}
l ${width / 2} 0
l ${-width / 2} ${width}
l ${-width / 2} ${-width}
Z
`
}
- 获取绘制箭头起始位置
export const getTriangleStart = (end) => {
return ({ ...end, y: end.y - 10 })
}
- 监听鼠标点击目标事件,获取起始位置
start = { x: 0, y: 0 }
window.addEventListener('mousedown', (event) => {
...
start = {
x: event.x,
y: event.y
}
})
- 监听鼠标移动事件
window.addEventListener('mousemove', (event) => {
...
let end = {
x: event.x,
y: event.y
}
this.linePath = computeLinePath(start, end, 0)
this.trianglePath = computeTrianglePath(getTriangleStart(end), 10)
})
- 页面展示
<svg class="processSvg-area">
<path :d="linePath" strokeWidth="1" fill="none" stroke='#7083ff'/>
<path :d='trianglePath' fill='#7083ff' stroke="none" />
</svg>
网友评论