Question

One of the requirements for some code I'm working on is to detect when the text in a Kinetic.Text box is too long and overflows/wraps and decrease the fontsize so it fits (horizontally).

I can't seem to determine when text would overflow/wrap in a Kinetic.Text.

The fontsize is the height of the text area. None of getHeight() getTextHeight() or lineHeight() seem to change when text starts to overflow/wrap.

Était-ce utile?

La solution

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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top