【问题标题】:How to add /n (new line) to string based on pixel width and limit characters based on pixel height如何根据像素宽度将 /n(新行)添加到字符串并根据像素高度限制字符
【发布时间】:2020-07-13 10:30:40
【问题描述】:

我想要做的是在 Javascript 中溢出给定像素宽度时在字符串中添加一个新行 (/n)。

文本是从 HTML 中的文本区域获取的,并且会根据选择的字体和字体大小而有所不同。最后的字符串将与 PIL 一起使用。

我还想限制输入长度,并能够根据像素宽度和高度向用户反馈剩余的字符空间。

有没有人知道任何可以提供这些功能的包或其他东西?

【问题讨论】:

  • 您能提供一些代码示例吗?
  • 问题是我还没有任何代码可以在 Javascript 中执行此操作。我看过画布,并将继续寻找是否有帮助。我正在寻找的是看看是否有人知道一些可以工作的JS包!
  • 您可以在画布元素上使用 measureText 来获取字符串的文本。 developer.mozilla.org/en-US/docs/Web/API/… 类似stackoverflow.com/questions/2936112/…
  • 感谢您的意见!我发现 pixi.js 可以测量字体的宽度和高度。它也使用画布,所以我可能也可以使用它!

标签: javascript html canvas html5-canvas python-imaging-library


【解决方案1】:

我创建了自己的解决方案。只是为了更新这篇文章,以防其他人使用它。到目前为止非常非常基本。很快就会继续下去,并希望更新更多。

它使用pixi.js 来获取字体指标。从那里它计算写入文本区域的文本,并根据可用像素区域计算使用多少空间的百分比。到目前为止只是一个快速草稿。但可能会帮助别人!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<p id="used-percentage"></p>
<div>
    <textarea id="editor"></textarea>
    <button id="button">Click me</button>

    <p id="string"></p>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.1.3/pixi.min.js"></script>
<script src="main.js"></script>

</body>
</html>

JS:

document.getElementById("editor").addEventListener("keypress", readText)

function readText(){
    let string = document.getElementById("editor").value;
    textMetrics(string)
}

function textMetrics(text){
    let style = new PIXI.TextStyle({fontFamily : 'Comic Sans MS', fontSize: 24, wordWrap: true, wordWrapWidth: 640})
    let textMetrics = PIXI.TextMetrics.measureText(text, style)
    console.log(textMetrics)

    // calculatePercentageUsed(textMetrics.maxLineWidth, textMetrics.height)

    calculatePixelUsed(textMetrics.lineWidths, textMetrics.lineHeight)
}

function calculatePixelUsed(lineWidths, lineHeight){
    let squaredLines = [];
    let squarepxUsed = 0;
    for (let i = 0; i < lineWidths.length; i++) {
        squaredLines[i] = lineWidths[i] * lineHeight;
        // console.log(squaredLines)
    }

    for (let j = 0; j < squaredLines.length; j++) {
        squarepxUsed += squaredLines[j];
        // console.log(squaredLines)
    }


    calculatePercentage(squarepxUsed)
}

function calculatePercentage(squarepxUsed) {
    let squarepxAvailable = 640 * 384
    let percentage = squarepxUsed / squarepxAvailable * 100
    document.getElementById("used-percentage").innerHTML = percentage
    // console.log(percentage)
}

CSS:

#editor {
width: 640px;
height: 384px;
font-family: "Comic Sans MS", sans-serif;
font-size: 24px;
}

演示: https://codepen.io/noodlesnort/pen/KKdgBQV

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2016-04-23
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    相关资源
    最近更新 更多