Skip to content

Commit 3da1450

Browse files
committed
fix: centralize text
Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com>
1 parent a121a58 commit 3da1450

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/components/Draw/TextInput.vue

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,36 @@ export default {
7272
ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height)
7373
ctx.fillStyle = 'black'
7474
ctx.font = "30px 'Dancing Script'"
75-
ctx.fillText(val, 15, 50)
75+
const paddingX = 15
76+
const maxWidth = Math.max(0, this.$refs.canvas.width - (paddingX * 2))
77+
const lineHeight = 36
78+
const words = String(val).trim().split(/\s+/).filter(Boolean)
79+
80+
const lines = []
81+
let line = ''
82+
for (const word of words) {
83+
const testLine = line ? `${line} ${word}` : word
84+
if (ctx.measureText(testLine).width <= maxWidth || !line) {
85+
line = testLine
86+
} else {
87+
lines.push(line)
88+
line = word
89+
}
90+
}
91+
if (line) {
92+
lines.push(line)
93+
}
94+
95+
ctx.textAlign = 'center'
96+
ctx.textBaseline = 'middle'
97+
98+
const totalHeight = lines.length * lineHeight
99+
const startY = (this.$refs.canvas.height / 2) - ((totalHeight - lineHeight) / 2)
100+
const centerX = this.$refs.canvas.width / 2
101+
102+
lines.forEach((text, index) => {
103+
ctx.fillText(text, centerX, startY + (index * lineHeight))
104+
})
76105
},
77106
},
78107
mounted() {

0 commit comments

Comments
 (0)