gpt4 book ai didi

javascript - html2canvas 去除多个空格和换行符

转载 作者:行者123 更新时间:2023-11-30 12:46:35 24 4
gpt4 key购买 nike

我正在使用 html2canvas 将 html 内容呈现为图像。但它只支持单词之间的单个空格,也支持所有文本只显示在一个中。

Example 1

if text is `Word1 Word2` it become to `word1 word2`

Example 2

This is First line
This is Second Line

Image:

THis is First line This is Second Line

我查看了 html2canvas 代码,我相信下面这两个函数负责绘制文本和空格。帮助我如何实现我的目标。

  function renderText(el, textNode, stack) {
var ctx = stack.ctx,
color = getCSS(el, "color"),
textDecoration = getCSS(el, "textDecoration"),
textAlign = getCSS(el, "textAlign"),
metrics,
textList,
state = {
node: textNode,
textOffset: 0
};

if (Util.trimText(textNode.nodeValue).length > 0) {
textNode.nodeValue = textTransform(textNode.nodeValue, getCSS(el, "textTransform"));
textAlign = textAlign.replace(["-webkit-auto"],["auto"]);

textList = (!options.letterRendering && /^(left|right|justify|auto)$/.test(textAlign) && noLetterSpacing(getCSS(el, "letterSpacing"))) ?
textNode.nodeValue.split(/(\b| )/)
: textNode.nodeValue.split("");

metrics = setTextVariables(ctx, el, textDecoration, color);

if (options.chinese) {
textList.forEach(function(word, index) {
if (/.*[\u4E00-\u9FA5].*$/.test(word)) {
word = word.split("");
word.unshift(index, 1);
textList.splice.apply(textList, word);
}
});
}

textList.forEach(function(text, index) {
var bounds = getTextBounds(state, text, textDecoration, (index < textList.length - 1), stack.transform.matrix);
if (bounds) {
drawText(text, bounds.left, bounds.bottom, ctx);
renderTextDecoration(ctx, textDecoration, bounds, metrics, color);
}
});
}
}

function drawText(currentText, x, y, ctx){
if (currentText !== null && Util.trimText(currentText).length > 0) {
ctx.fillText(currentText, x, y);
numDraws+=1;
}
}

最佳答案

html2canvas 在一行中渲染文本区域或输入框值,并 trim 所有超过一个单词之间的空格。所以我通过将文本区域转换为 div 标签找到了解决方案,查看 html contenteditable Attribute

 Replace  <textarea></textarea> with <div contenteditable="true"></div>

如果你想使用 jquery 使 textarea 行为与 div 相同,请使用此代码

$( '#EDITABLE' ).focus();

var selection = window.getSelection();
var range = document.createRange();
var div = $('#div2').get(0);

range.setStartBefore(div);
range.collapse(true);

selection.removeAllRanges();
selection.addRange(range);

// cursor should now be between div1 and div2
range = window.getSelection().getRangeAt(0);
console.log("range object returned is: ", range);

参见示例:http://jsfiddle.net/9ZZpX/3/

关于javascript - html2canvas 去除多个空格和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com