本文介绍了在< canvas>元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用< canvas>
元素在图片上加入文字。首先绘制图像,并在图像上绘制文本。到目前为止这么好。
I am trying to add text on an image using the <canvas>
element. First the image is drawn and on the image the text is drawn. So far so good.
但是我面临的一个问题是,如果文本太长,它会在画布的开始和结束处截断。我不打算调整画布大小,但我想知道如何将长文本包装成多行,以便所有它显示。
But where I am facing a problem is that if the text is too long, it gets cut off in the start and end by the canvas. I don't plan to resize the canvas, but I was wondering how to wrap the long text into multiple lines so that all of it gets displayed. Can anyone point me at the right direction?
推荐答案
一种可能的方法(未完全测试,但现在它工作得很好)
A possible method (not completely tested, but as for now it worked perfectly)
/**
* Divide an entire phrase in an array of phrases, all with the max pixel length given.
* The words are initially separated by the space char.
* @param phrase
* @param length
* @return
*/
function getLines(ctx,phrase,maxPxLength,textStyle) {
var wa=phrase.split(" "),
phraseArray=[],
lastPhrase=wa[0],
measure=0,
splitChar=" ";
if (wa.length <= 1) {
return wa
}
ctx.font = textStyle;
for (var i=1;i<wa.length;i++) {
var w=wa[i];
measure=ctx.measureText(lastPhrase+splitChar+w).width;
if (measure<maxPxLength) {
lastPhrase+=(splitChar+w);
} else {
phraseArray.push(lastPhrase);
lastPhrase=w;
}
if (i===wa.length-1) {
phraseArray.push(lastPhrase);
break;
}
}
return phraseArray;
}
这篇关于在< canvas>元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!