meta2d.js
meta2d.js copied to clipboard
扩展实现一个多条线合并成一条线的功能遇到的问题
Code Sanbox异常重现
No response
bug描述
我想实现一个合并线段的功能,参考了核心库源码
选中有重合的锚点的两根线
点击合并后鼠标放上去可以看到锚点,但是第二个线段没有渲染
下面是代码 // 点击合并线段按钮检查选中状态满足条件就合并
if (selections.pens) {
// 选中了两根线且两根线有一个重合的锚点时
const lines = selections.pens.filter((v) => v.type === PenType.Line)
if (lines.length === 2) {
// 首先根据坐标排序,以最左边第一条线的样式为准
const sortLines = lines.sort((a, b) => {
return a.x! - b.x!
})
const [firstLine, lastLine] = sortLines
const allAnchors = [
...(firstLine.calculative?.worldAnchors || []),
...(lastLine.calculative?.worldAnchors || [])
]
// 找出重合点 先人为保证线有且只有一个重合的点
const findSameAnchor = allAnchors.find((v, index) => {
return allAnchors.some((fv, fIndex) => {
if (index !== fIndex) {
return v.id === fv.id || v.id === fv.anchorId
}
return false
})
})
if (findSameAnchor) {
let newAnchors = []
// 找出重合点在第一根线的索引
const findFirstIndex = firstLine.calculative?.worldAnchors?.findIndex((v) => {
const matchId = findSameAnchor.anchorId || findSameAnchor.id
if (matchId === v.anchorId || matchId === v.id) {
return true
}
})
// console.log(findFirstIndex)
if (findFirstIndex === 0) {
newAnchors = (firstLine.calculative?.worldAnchors || []).reverse()
} else {
newAnchors = [...(firstLine.calculative?.worldAnchors || [])]
}
newAnchors[newAnchors.length - 1].connectTo = undefined
const findLastIndex = lastLine.calculative?.worldAnchors?.findIndex((v) => {
const matchId = findSameAnchor.anchorId || findSameAnchor.id
if (matchId === v.anchorId || matchId === v.id) {
return true
}
})
let conctAnchors = []
if (findLastIndex === 0) {
conctAnchors = (lastLine.calculative?.worldAnchors || []).slice(1)
} else {
conctAnchors = (lastLine.calculative?.worldAnchors || []).reverse().slice(1)
}
newAnchors = [
...newAnchors.map((v) => ({ ...v })),
...conctAnchors.map((v) => {
return {
...v,
penId: firstLine.id
}
})
]
meta2d.delete([lastLine as any])
firstLine.calculative!.worldAnchors = newAnchors
// 这里是看到另外的一处源码加的方法initLineRect 加入这个方法线的数据合并成功了,但是画布上第二条线是空白的,拖动一下就显示出来了
meta2d.canvas.initLineRect(firstLine as any)
meta2d.render()
}
期待效果
合并线段以后可以和官方提供的按照ALT键合并以后的效果一样两条线变成一条线
发生频率
每次
核心库版本
"@meta2d/core": "^1.0.24",
浏览器版本
chrome 115.0.5790.170
其他需要补充的
感谢开源,请求协助
给个 codesandbox ? 没有你的上下文,是很难看出来问题的,直接看的话,感觉没问题