Fabricjs 固定文本框

pro*_*010 5 javascript fabricjs

如何固定文本框的大小以防止它在键入时溢出其大小(固定宽度和高度)?

var canvas = window._canvas = new fabric.Canvas('c');

var text = new fabric.Textbox('MyText', {
    width: 300,
    height: 300,
    top: 5,
    left: 5,
    hasControls: false,
    fontSize: 30,
    fixedWidth: 300,
    fixedFontSize: 30
});
canvas.add(text);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/643qazk0/2/

tar*_*s-d 3

您可以重写insertChars方法并检查文本溢出。

请参阅下面的片段。

// Create canvas
const canvas = new fabric.Canvas(document.querySelector('canvas'));

// Define `LimitedTextbox` class which extends `Textbox`
const LimitedTextbox = fabric.util.createClass(fabric.Textbox, {

  // Override `insertChars` method
  insertChars: function(chars) {

    if (this.maxWidth) {
      const textWidthUnderCursor = this._getLineWidth(this.ctx, this.get2DCursorLocation().lineIndex);
      if (textWidthUnderCursor + this.ctx.measureText(chars).width > this.maxWidth) {
        chars = '\n' + chars;
      }
    }

    if (this.maxLines) {
      const newLinesLength = this._wrapText(this.ctx, this.text + chars).length;
      if (newLinesLength > this.maxLines) {
        return;
      }
    }

    // Call parent class method
    this.callSuper('insertChars', chars);
  }

});

// Create limited text box with max width 300px and max 2 lines
canvas.add(
  new LimitedTextbox('text', {
    top: 10,
    left: 10,
    width: 300,
    maxWidth: 300,
    maxLines: 2
  })
);

canvas.renderAll();
Run Code Online (Sandbox Code Playgroud)
.canvas-container {
  border: 1px solid gray;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>

<canvas width="600" height="300"></canvas>
Run Code Online (Sandbox Code Playgroud)

使用 Fabric 1.7.20 进行测试

  • 对于 2.4.6 版本如何实现这一点,有什么建议吗?这两个版本的 insertChar 函数都不同,因此在两个版本中都不能按预期工作 (2认同)