我正在处理的某些代码的一个要求是检测Kinetic.Text框中的文本何时太长并溢出/换行并减少字体大小以使其适合(水平)。
我似乎无法确定何时文本会溢出/包裹在Kinetic.Text中。
fontsize是文本区域的高度。当文本开始溢出/换行时,getHeight()getTextHeight()或lineHeight()似乎都没有改变。
答案 0 :(得分:3)
html canvas上下文有一个measureText方法,用于测量指定文本的宽度。
这是一个将changeText方法添加到Kinetic.Text的示例。
当文本超过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();