我正在编写的某些代码的要求之一是检测 Kinetic.Text 框中的文本何时太长并溢出/换行,并减小字体大小以使其适合(水平)。
我似乎无法确定文本何时会在 Kinetic.Text 中溢出/换行。
字体大小是文本区域的高度。当文本开始溢出/换行时, getHeight() getTextHeight() 或 lineHeight() 似乎都没有改变。
最佳答案
html canvas 上下文有一个measureText 方法,可以测量指定文本的宽度。
这是一个向 Kinetic.Text 添加 changeText 方法的示例。
当文本超过 maxLineWidth 时,changeText 方法会通过添加换行符来换行指定的文本。
演示:http://jsfiddle.net/m1erickson/MTQRV/
// create an offscreen canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
// create a Kinetic.Text object
var wrappedText = new Kinetic.Text({
x: 10,
y: 30,
fill: 'black',
fontSize: 14,
fontFamily: "Verdana",
text: "testing..."
});
// add a maxLineWidth property to the text node
wrappedText.maxLineWidth = 250; // pixels
// add a changeText method to the text node
// this method will wrap the specified text
// within maxLineWidth by adding newline characters
wrappedText.changeText = function (text) {
var maxLength = this.maxLineWidth;
ctx.font = this.getFontSize() + " " + this.getFontFamily();
var words = text.split(" ");
var wrapped = "";
var line = "";
for (var i = 0; i < words.length; i++) {
if (ctx.measureText(line + " " + words[i]).width > maxLength) {
wrapped += (line + "\n");
line = "";
}
line += " " + words[i];
}
wrapped += line;
this.setText(wrapped);
layer.draw();
}
layer.add(wrappedText);
// TESTING
wrappedText.changeText(someText);
layer.draw();
关于javascript - 如何检测文本何时溢出/换行 Kinetic.Text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124538/