1

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

Jplus2
  • 2,216
  • 2
  • 28
  • 49
  • why you want to change? – Durga Aug 10 '18 at 06:08
  • @Durga I wanted to fire or perform an action every time they hit enter key on an IText object, inside editing mode of course, but still proceed on adding the carriage return character after. Hope that answers your question. – Jplus2 Aug 10 '18 at 06:43

1 Answers1

5

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>
Durga
  • 15,263
  • 2
  • 28
  • 52