work page
Canvasテキストを折り返す
YOUR CODE:
ctx.font = '40px "Noto Sans JP"';
ctx.fillText(text, 0, 50, 400);
「正しく改行する」には追加の処理が必要
自動で折り返す機能はないので、Intl.Segmenterで単語に分け、単語ごとにmeasureText()で幅を計測しながら描画します。
欧文のハイフネーションや和文の禁則処理も必要な場合、さらに追加の実装が必要です。
for (const { segment } of segments) {
const nextLine = line + segment;
if (ctx.measureText(nextLine).width > 400) {
ctx.fillText(line.trimEnd(), 0, y);
line = segment.trimStart();
y += lineHeight;
} else {
line = nextLine;
}
}