diff --git a/src/app/util/canvas-util.js b/src/app/util/canvas-util.js index 86e07752..c052986b 100644 --- a/src/app/util/canvas-util.js +++ b/src/app/util/canvas-util.js @@ -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 +} diff --git a/src/components/Roof.jsx b/src/components/Roof.jsx index ebe9dedc..0ff0e9ba 100644 --- a/src/components/Roof.jsx +++ b/src/components/Roof.jsx @@ -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() { > 도형반전 +
{ // 현재 마우스 포인터의 위치를 가져옵니다. 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, } }