canvasfabricjsdom-eventskeydowncleartext

How i can introduce key based event in my fabric.js canvas?


I am following the below js fiddle. https://jsfiddle.net/Jonah/sbtoukan/1/

The code I am following is as below:

var canvas = new fabric.Canvas('container');
var oText = new fabric.IText('Tap and Type', {
     left: 0,
     top: 0,
     fontFamily: 'Bree Serif',
     fontSize: 22,
     cache: false
});

canvas.on("mouse:over", clearText);
function clearText(e) {
    if (e.target.type === "i-text") {
        if (e.target.text === "Tap and Type") {
        e.target.text = "";
        canvas.renderAll();
    };
}

canvas.add(oText);

In the above code I am implementing mouse related event such as I am implementing mouse:over. When I hover the mouse on text then I am successfully implementing the cleartext function.

But I want that when I press some key then it should clear the text.

I reviewed this link:- https://github.com/fabricjs/fabric.js/wiki/Working-with-events to add mouse:over functionality, but I did not get that how to add keydown event in my fabric canvas. Please help.


Solution

  • There are no key press events on the canvas, so we have to set them on the document and grab the selected object on the mouse over and reset on the mouse out event.

    var canvas = new fabric.Canvas('container');
    var oText = new fabric.IText('Tap and Type', {left: 0, top: 0});
    canvas.add(oText);
    var circle = new fabric.Circle({left: 20, top: 90, radius: 25});
    canvas.add(circle);
    
    var objSelected = null
    
    canvas.on("mouse:over", function(e) {
      if (e.target) {
        e.target.set('fill', 'green');
        canvas.renderAll();
        objSelected = e.target
      }
    });
    
    canvas.on('mouse:out', function(e) {
      if (e.target) {
        e.target.set('fill', 'black');
        canvas.renderAll();
      }
      objSelected = null
    });
    
    document.onkeydown = function(e) {
      if (objSelected) {
        switch (e.keyCode) {
          case 46: // delete
            if (objSelected.type === "i-text") {
              objSelected.text = ""
            }
        }
        canvas.renderAll();
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.1/fabric.min.js">
    </script>
    
    <canvas id="container" width="300" height="150"></canvas>

    The issue with the key press events is that sometimes the focus is not where you think, iframes are particularly tricky on that, on this example make sure you click on the canvas before you try the delete key.