给定一个
<div id="e83v8" style="width: 86px; background-color: red; font-size: 10px; overflow-wrap: word-break; hyphens: auto;">This is a text that is long enough to cause a line break if set so. By using words like "incomprehensibilities", we can demonstrate word breaks.</div>
我想使用 JavaScript 访问带有连字符的格式化文本,以获得类似于
"This is a text that is long enough to cause a line break if set so. By using words like "incomprehensibilit-ies", we can demon-strate word breaks."
的字符串。这可能吗?
用例是我需要一种方法,仅使用 SVG 元素即可在 SVG 的
<text>
元素中断开和连字符文本。
也许可以尝试一下
const wrapText = (context, text, x, y, maxWidth, lineHeight) => {
const words = text.split(' ');
let line = '';
words.forEach(word => {
const testLine = line + word + ' ';
const {
width: testWidth
} = context.measureText(testLine);
if (testWidth > maxWidth && line !== '') {
context.fillText(line, x, y);
line = word + ' ';
y += lineHeight;
} else {
line = testLine;
}
});
context.fillText(line, x, y); // Render the last line
};
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
const maxWidth = 400;
const lineHeight = 25;
const x = (canvas.width - maxWidth) / 2;
const y = 60;
const text = document.getElementById('e83v8').textContent;
context.font = '16pt Calibri';
context.fillStyle = '#333';
wrapText(context, text, x, y, maxWidth, lineHeight);
<div id="e83v8" style="width: 86px; background-color: red; font-size: 10px; overflow-wrap: word-break; hyphens: auto;">This is a text that is long enough to cause a line break if set so. By using words like "incomprehensibilities", we can demonstrate word breaks.</div>
<canvas id="myCanvas" width="500" height="200"></canvas>