javascript - 如何检测文本何时溢出/换行 Kinetic.Text?

标签 javascript kineticjs

我正在编写的某些代码的要求之一是检测 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/

相关文章:

javascript - 通过 JavaScript 设置文件输入的值会触发看似无关的事件

javascript - 添加另一个形状时,动力学 JS 形状阴影变得更加明显

javascript - KineticJs 不同 Angular 旋转

javascript - 如何在 KineticJS Wedge 中垂直居中文本?

kineticjs - 如何应用 KineticJS 过滤器?

javascript - 无法更新 "data-attribute"值

javascript - XMLHttpRequest 无法加载 Access-Control-Allow-Origin 不允许的来源

javascript - Sass 加载器和 webpack 4

javascript - angular.js - 解析 html 函数需要 2000 毫秒甚至更多

javascript - KineticJS 创建 Canvas