Search code examples
fabricjsfabricjs2

How to add key press listener for IText objects in FabricJS?


I currently have this code

fabric.IText.prototype.keysMap[13] = 'onEnterKeyPress';
fabric.IText.prototype.onEnterKeyPress = (e) => {
  console.log('onEnterKeyPress', e);
  // this.insertChars(e);
  // fabric.IText.insertChars(e);
  // return true;
  // return e;
};
  
let canvas = new fabric.Canvas('canvas', {
  preserveObjectStacking: true,
  width: 980,
  height: 600
});

let itext = new fabric.IText(
  'Edit this text',
  {
    editable: true,
    left: 100,
    top: 100,
    fontSize: 24
  }
);

canvas.add(itext);
canvas.requestRenderAll();
<html>
  <body>
    <canvas id="canvas"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.4/fabric.min.js"></script>
  </body>
</html>

The issue is, once I attached the key press listener, if I hit enter key, it does fire my function callback but it won't add the carriage return character in the text.

If I remove my key press listener, it does go back to normal, that is adding the carriage return character on enter key press.

It seems I have to manually add the carriage return when I attached a key press listener? Not sure how to do it tho.

Thanks in advance.

BTW I'm using latest of FabricJS 2.3.4


Solution

  • You can override onKeyDown, then call original method.

    DEMO*

    fabric.IText.prototype.onKeyDown = (function(onKeyDown) {
      return function(e) {
        if (e.keyCode == 13)
          console.log('enter key');
        onKeyDown.call(this, e);
      }
    })(fabric.IText.prototype.onKeyDown)
    
    let canvas = new fabric.Canvas('canvas', {
      preserveObjectStacking: true,
      width: 980,
      height: 600
    });
    
    let itext = new fabric.IText(
      'Edit this text', {
        editable: true,
        left: 100,
        top: 100,
        fontSize: 24
      }
    );
    
    canvas.add(itext);
    canvas.requestRenderAll();
    <html>
      <body>
        <canvas id="canvas"></canvas>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.4/fabric.js"></script>
      </body>
    </html>