Urgent.News

What's breaking now, across hundreds of outlets.

Tech

A naive canvas text wrap put punctuation at the start of 3 of 7 lines in one Chinese sample

If you draw text on a canvas, a common first wrapping function is: measure the line so far, and when the next character no longer fits, start a new line. On plain Chinese it looks fine. On one punctuation-heavy sample it put a closing quote, a closing bracket and an enumeration comma at the start of lines, 3 of the 7 lines at a 200px width. This post is what I learned about why that is wrong, and…

When drawing text on a canvas using a common wrapping function, the placement of punctuation marks at the start of lines can sometimes create unexpected results. In one Chinese example, a closing quote, closing bracket, and enumeration comma appeared at the beginning of three out of seven lines when the canvas width was set to 200 pixels.

This unintended behavior occurs because the function measures the line and breaks when the next character no longer fits within the width limit. To understand why this happens, it's important to know which characters should not be allowed to start a line. These include punctuation marks such as 、。、;:?!)》」』】〉…—~, as well as opening brackets like (《「『【〈 and closing quotes.

The naive approach of simply wrapping text based on width doesn't account for these characters, leading to incorrect line breaks. The solution is to tokenize the text, treating each Chinese or Japanese character as its own token and grouping English words or numbers together. When a line would start with a forbidden character, pull the last token from the previous line down with it.

This adjustment made the token-based approach match the browser's default layout in most cases, although there were still some discrepancies, particularly with the em dash character. To accurately replicate the behavior of a browser's text layout, it's essential to use tokenization and apply the appropriate rules for starting and ending lines.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

More from Dev.to on urgent.news

Report a problem with this story

Get the day's news by email. Daily, weekly or monthly. Sign up

More in Tech

More from Thursday, 3 December 2026 →