숫자 있는 선 추가

This commit is contained in:
hyojun.choi 2024-06-19 15:01:41 +09:00
parent ae181f1d69
commit 67f519d6fa
3 changed files with 63 additions and 1 deletions

View File

@ -77,3 +77,23 @@ export function anchorWrapper(anchorIndex, fn) {
export const getDistance = (x1, y1, x2, y2) => {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2))
}
// 선의 길이를 계산하는 함수
export const calculateLineLength = (x1, y1, x2, y2) => {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2))
}
// 선과 텍스트를 그룹으로 묶는 함수
export const createGroupWithLineAndText = (line, text) => {
return new fabric.Group([line, text])
}
export const calculateShapeLength = (shape) => {
// 도형의 원래 길이를 가져옵니다.
const originalLength = shape.width
// 도형의 scaleX 값을 가져옵니다.
const scaleX = shape.scaleX
// 도형의 현재 길이를 계산합니다.
return originalLength * scaleX
}

View File

@ -1,4 +1,4 @@
import { getDistance } from '@/app/util/canvas-util'
import { createGroupWithLineAndText, getDistance } from '@/app/util/canvas-util'
import { useCanvas } from '@/hooks/useCanvas'
import { fabric } from 'fabric'
import { v4 as uuidv4 } from 'uuid'
@ -18,6 +18,7 @@ export default function Roof() {
attachCustomControlOnPolygon,
saveImage,
handleFlip,
updateTextOnLineChange,
} = useCanvas('canvas')
const addRect = () => {
@ -107,6 +108,31 @@ export default function Roof() {
addShape(trapezoid)
}
const addTextWithLine = () => {
const { x1, y1, x2, y2 } = { x1: 20, y1: 100, x2: 220, y2: 100 }
/**
* 시작X,시작Y,도착X,도착Y 좌표
*/
const horizontalLine = new fabric.Line([x1, y1, x2, y2], {
name: uuidv4(),
stroke: 'red',
strokeWidth: 3,
selectable: true,
})
const text = new fabric.Text(getDistance(x1, y1, x2, y2).toString(), {
fontSize: 20,
left: (x2 - x1) / 2,
top: y1 - 20,
})
const group = createGroupWithLineAndText(horizontalLine, text)
addShape(group)
// .
group.on('modified', () => updateTextOnLineChange(group, text))
}
const randomColor = () => {
return '#' + Math.round(Math.random() * 0xffffff).toString(16)
}
@ -206,6 +232,12 @@ export default function Roof() {
>
도형반전
</button>
<button
className="w-30 mx-2 p-2 rounded bg-black text-white"
onClick={addTextWithLine}
>
숫자가 있는
</button>
</div>
<div

View File

@ -3,6 +3,7 @@ import { fabric } from 'fabric'
import {
actionHandler,
anchorWrapper,
calculateShapeLength,
polygonPositionHandler,
} from '@/app/util/canvas-util'
@ -164,6 +165,7 @@ export function useCanvas(id) {
const handleMouseDown = (e) => {
// 현재 마우스 포인터의 위치를 가져옵니다.
if (canvas?.getActiveObject()) {
points.current = []
return
}
const pointer = canvas?.getPointer(e.e)
@ -492,6 +494,13 @@ export function useCanvas(id) {
canvas?.renderAll()
}
// 선의 길이가 변경될 때마다 텍스트를 업데이트하는 함수
const updateTextOnLineChange = (group, text) => {
const length = calculateShapeLength(group)
text.set({ text: length.toString() })
canvas?.renderAll()
}
return {
canvas,
addShape,
@ -506,5 +515,6 @@ export function useCanvas(id) {
attachCustomControlOnPolygon,
saveImage,
handleFlip,
updateTextOnLineChange,
}
}