使用 JavaScript 访问 HTML 元素显示的连字符

问题描述 投票:0回答:1

给定一个

<div
  lang="en"
  style="
    overflow-wrap: word-break;
    hyphens: auto;
    width: 86px;
    background-color: highlight;
    color: highlightText;
    font-size: 10px;
  ">
    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."
.

注意

incomprehensibilit-ies" and 
demon-strate`中的连字符。

这可能吗?

用例是我需要一种方法,仅使用 SVG 元素即可在 SVG 的

<text>
元素中断开和连字符文本。

javascript svg
1个回答
-1
投票

也许可以尝试一下

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>

© www.soinside.com 2019 - 2024. All rights reserved.