qcast-front/src/hooks/useLine.js

81 lines
1.7 KiB
JavaScript

import { useRecoilValue } from 'recoil'
import { canvasState, fontFamilyState, fontSizeState } from '@/store/canvasAtom'
import { QLine } from '@/components/fabric/QLine'
export const useLine = () => {
const canvas = useRecoilValue(canvasState)
const fontSize = useRecoilValue(fontSizeState)
const fontFamily = useRecoilValue(fontFamilyState)
const addLine = (points = [], options) => {
const line = new QLine(points, {
...options,
fontSize: fontSize,
fontFamily: fontFamily,
})
if (line.length === 0) {
return null
}
canvas?.add(line)
return line
}
const hideLine = (line) => {
line.set({
visible: false,
})
canvas
?.getObjects()
.find((obj) => obj.parent === line)
.set({
visible: false,
})
canvas?.renderAll()
}
const showLine = (line) => {
line.set({
visible: true,
})
canvas
?.getObjects()
.find((obj) => obj.parent === line)
.set({
visible: true,
})
canvas?.renderAll()
}
const removeLine = (line) => {
removeLineText(line)
canvas?.remove(line)
canvas?.renderAll()
}
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,
hideLine,
showLine,
}
}