65 lines
1.5 KiB
JavaScript
65 lines
1.5 KiB
JavaScript
import { useRecoilValue } from 'recoil'
|
|
import { canvasState, fontFamilyState, fontSizeState } from '@/store/canvasAtom'
|
|
|
|
export const useLine = () => {
|
|
const canvas = useRecoilValue(canvasState)
|
|
const fontSize = useRecoilValue(fontSizeState)
|
|
const fontFamily = useRecoilValue(fontFamilyState)
|
|
|
|
const addLine = (points = [], options) => {
|
|
const line = new fabric.Line(points, {
|
|
...options,
|
|
selectable: options.selectable ?? false,
|
|
})
|
|
|
|
canvas?.add(line)
|
|
addLineText(line)
|
|
return line
|
|
}
|
|
|
|
const addLineText = (line, length = getLengthByLine(line)) => {
|
|
removeLineText(line)
|
|
|
|
const lengthTxt = isNaN(Number(length)) ? length : length.toFixed(0)
|
|
|
|
const text = new fabric.Text(lengthTxt, {
|
|
left: (line.x2 + line.x1) / 2,
|
|
top: (line.y2 + line.y1) / 2,
|
|
parent: line,
|
|
name: 'lengthTxt',
|
|
fontSize: fontSize,
|
|
fontFamily: fontFamily,
|
|
})
|
|
|
|
canvas?.add(text)
|
|
return text
|
|
}
|
|
|
|
const removeLine = (line) => {
|
|
removeLineText(line)
|
|
canvas?.remove(line)
|
|
}
|
|
|
|
const removeLineText = (line) => {
|
|
canvas?.remove(canvas?.getObjects().find((obj) => obj.parent === line))
|
|
}
|
|
|
|
const getLengthByLine = (line) => {
|
|
const scaleX = line.scaleX
|
|
const scaleY = line.scaleY
|
|
const x1 = line.left
|
|
const y1 = line.top
|
|
const x2 = line.left + line.width * scaleX
|
|
const y2 = line.top + line.height * scaleY
|
|
const dx = x2 - x1
|
|
const dy = y2 - y1
|
|
|
|
return Number(Math.sqrt(dx * dx + dy * dy).toFixed(1)) * 10
|
|
}
|
|
|
|
return {
|
|
addLine,
|
|
removeLine,
|
|
}
|
|
}
|