( ctx: CanvasRenderingContext2D, text: string, maxWidth: number )
| 12 | |
| 13 | // Helper function to wrap text |
| 14 | const wrapText = ( |
| 15 | ctx: CanvasRenderingContext2D, |
| 16 | text: string, |
| 17 | maxWidth: number |
| 18 | ): string[] => { |
| 19 | // Check if the text contains any Chinese characters |
| 20 | const containsChinese = /[\u4e00-\u9fa5]/.test(text); |
| 21 | const punctuation = [ |
| 22 | ".", |
| 23 | ",", |
| 24 | "!", |
| 25 | "?", |
| 26 | ";", |
| 27 | ":", |
| 28 | "。", |
| 29 | "!", |
| 30 | ",", |
| 31 | "、", |
| 32 | ";", |
| 33 | ":", |
| 34 | ]; |
| 35 | |
| 36 | const lines: string[] = []; |
| 37 | let currentLine = ""; |
| 38 | |
| 39 | if (containsChinese) { |
| 40 | // For Chinese text, wrap character by character |
| 41 | for (let i = 0; i < text.length; i++) { |
| 42 | const char = text[i]; |
| 43 | const testLine = currentLine + char; |
| 44 | const metrics = ctx.measureText(testLine); |
| 45 | |
| 46 | if (metrics.width > maxWidth && currentLine !== "") { |
| 47 | if (punctuation.includes(char)) { |
| 48 | currentLine += text[i]; |
| 49 | lines.push(testLine); |
| 50 | currentLine = ""; |
| 51 | } else { |
| 52 | lines.push(currentLine); |
| 53 | currentLine = char; |
| 54 | } |
| 55 | } else { |
| 56 | currentLine = testLine; |
| 57 | } |
| 58 | } |
| 59 | } else { |
| 60 | // For non-Chinese text, wrap word by word |
| 61 | const words = text.split(" "); |
| 62 | |
| 63 | for (const word of words) { |
| 64 | const separator = currentLine === "" ? "" : " "; |
| 65 | const testLine = currentLine + separator + word; |
| 66 | const metrics = ctx.measureText(testLine); |
| 67 | |
| 68 | if (metrics.width > maxWidth && currentLine !== "") { |
| 69 | lines.push(currentLine); |
| 70 | currentLine = word; |
| 71 | } else { |
no outgoing calls
no test coverage detected