Skip to content

Commit 588d42f

Browse files
authored
Add wrapSVGTextCentered function for centered text
1 parent 5f944dd commit 588d42f

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

utils/allFunction.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,30 @@ function wrapSVGText(text, maxCharsPerLine = 25, lineHeight = 16) {
1818
).join("");
1919
}
2020

21+
function wrapSVGTextCentered(text, maxCharsPerLine = 25, lineHeight = 16, svgHeight = 400, svgWidth = 600) {
22+
const words = text.split(" ");
23+
const lines = [];
24+
let line = "";
25+
26+
for (let w of words) {
27+
if ((line + w).length > maxCharsPerLine) {
28+
lines.push(line.trim());
29+
line = w + " ";
30+
} else {
31+
line += w + " ";
32+
}
33+
}
34+
if (line) lines.push(line.trim());
35+
36+
const totalHeight = lines.length * lineHeight;
37+
const startY = (svgHeight - totalHeight) / 2; // posisi vertikal awal
38+
39+
return lines.map((l, i) =>
40+
`<tspan x="${svgWidth / 2}" dy="${i === 0 ? startY : lineHeight}" text-anchor="middle">${l}</tspan>`
41+
).join("");
42+
}
43+
44+
2145

2246
function capitalize(str = "") {
2347
str = str.toLowerCase()
@@ -26,4 +50,4 @@ function capitalize(str = "") {
2650

2751

2852

29-
module.exports = { wrapSVGText, capitalize };
53+
module.exports = { wrapSVGText, wrapSVGTextCentered, capitalize };

0 commit comments

Comments
 (0)