2024-07-04 16:11:23 +09:00

86 lines
2.0 KiB
JavaScript

import { fabric } from 'fabric'
export default class QLine extends fabric.Line {
length
#text
#viewLengthText
#fontSize
type = 'QLine'
constructor(points, option) {
if (!option.fontSize) {
throw new Error('Font size is required.')
}
super(points, option)
this.#fontSize = option.fontSize
this.#init(option)
this.#addControl()
}
#init(option) {
// 선의 길이를 계산하여 length 속성을 초기화합니다.
const dx = this.x2 - this.x1
const dy = this.y2 - this.y1
this.length = Number(Math.sqrt(dx * dx + dy * dy).toFixed(0))
this.#viewLengthText = option.viewLengthText ?? true
}
#addControl() {
this.on('added', () => {
this.#addLengthText()
})
this.on('moving', () => {
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 = Number(length.toFixed(0)) // 선의 길이를 length 속성에 저장합니다.
this.#addLengthText()
})
this.on('removed', () => {
this.canvas.remove(this.#text)
this.#text = null
})
}
setViewLengthText(bool) {
this.#viewLengthText = bool
this.#addLengthText()
}
setFontSize(fontSize) {
this.#fontSize = fontSize
this.#addLengthText()
}
#addLengthText() {
if (this.#text) {
this.canvas.remove(this.#text)
}
if (this.#viewLengthText) {
const text = new fabric.Text(this.length.toString(), {
left: (this.x1 + this.x2) / 2,
top: (this.y1 + this.y2) / 2,
fontSize: this.#fontSize,
selectable: false,
})
this.#text = text
this.canvas.add(text)
}
}
}