diff --git a/src/components/Roof2.jsx b/src/components/Roof2.jsx index 4469cc67..19c64337 100644 --- a/src/components/Roof2.jsx +++ b/src/components/Roof2.jsx @@ -46,16 +46,12 @@ export default function Roof2() { const makeLine = () => { if (canvas) { - const line = new QLine([50, 50, 200, 200], { + const line = new QLine([50, 50, 200, 50], { stroke: 'black', strokeWidth: 2, - viewLengthText: true, // 이 속성이 true로 설정되면, 선분의 길이를 표시하는 텍스트가 생성됩니다. - selectable: false, }) canvas?.add(line) - - setTimeout(() => line.delete(), 500) } } diff --git a/src/components/fabric/QLine.js b/src/components/fabric/QLine.js index 10021aa6..8beda276 100644 --- a/src/components/fabric/QLine.js +++ b/src/components/fabric/QLine.js @@ -1,56 +1,65 @@ import { fabric } from 'fabric' + export default class QLine extends fabric.Line { length - group + text constructor(points, option) { super(points, option) + this.#init(option) + this.#addControl() + } + #init(option) { + // 선의 길이를 계산하여 length 속성을 초기화합니다. + const dx = this.x2 - this.x1 + const dy = this.y2 - this.y1 + this.length = Math.sqrt(dx * dx + dy * dy).toFixed(0) + this.viewLengthText = option.viewLengthText ?? true + } + + #addControl() { this.on('added', () => { - if (this.viewLengthText) { - this.#addLengthText() - } else { - this.#makeGroupItem([this]) - } + this.#addLengthText() + }) + + this.on('modified', (e) => { + const scaleX = this.scaleX + const scaleY = this.scaleY + + // x1, y1, x2, y2 속성을 새로운 좌표로 설정합니다. + this.x1 = this.left + this.y1 = this.top + this.x2 = this.left + this.width * scaleX + this.y2 = this.top + this.height * scaleY + + const dx = this.x2 - this.x1 + const dy = this.y2 - this.y1 + const length = Math.sqrt(dx * dx + dy * dy) + this.length = length.toFixed(0) // 선의 길이를 length 속성에 저장합니다. + this.#addLengthText() }) } - delete() { - this.group.canvas.remove(this.group) - } - - #makeGroupItem(groupItems) { - const group = new fabric.Group(groupItems, { - selectable: false, - type: 'QRect', - group: this.selectable, - canvas: this.canvas, - }) - - this.group = group - this.canvas.add(group) - this.canvas.renderAll() - this.canvas.remove(this) + setViewLengthText(bool) { + this.viewLengthText = bool + this.#addLengthText() } #addLengthText() { - const dx = this.x2 - this.x1 - const dy = this.y2 - this.y1 - const length = Math.sqrt(dx * dx + dy * dy) + if (this.text) { + this.canvas.remove(this.text) + } - this.length = length.toFixed(0) - - const text = new fabric.Text(this.length, { - left: (this.x1 + this.x2) / 2, - top: (this.y1 + this.y2) / 2, - fontSize: 16, - selectable: false, - }) - - this.#makeGroupItem([this, text]) - } - - getInfo() { - return this + if (this.viewLengthText) { + const text = new fabric.Text(this.length, { + left: (this.x1 + this.x2) / 2, + top: (this.y1 + this.y2) / 2, + fontSize: 16, + selectable: false, + }) + this.text = text + this.canvas.add(text) + } } }