The html canvas context has a measureText method that will measure the width of specified text.
Here's an example that adds a changeText method to Kinetic.Text.
The changeText method causes specified text to be wrapped by adding newline characters when the text would exceed a maxLineWidth.
A Demo: 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();