How I can change my clearText default click event to a keypress event in fabric.js?

418 Views Asked by At

I am following the below js fiddle. I am perfectly running it. https://jsfiddle.net/Jonah/sbtoukan/1/ But in the above link the text is cleared when I click on the text. I want to clear the text only when I press the delete key. I tried several ways. But nothing working for me. Below is the exact code which is only allowing me to clear the text after clicking on the text.

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("text:editing:entered", 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);
1

There are 1 best solutions below

3
On

You need to the added an event handler for the delete key. If the delete key is pressed then only text will be cleared.

You can use the below code snippet. Hope it helps!

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("text:editing:entered", clearText);

function clearText(e) {
  if (e.target.type === "i-text") {
    if (e.target.text === "Tap and Type") {
    document.addEventListener("keypress", function(event) {
        if (event.keyCode == 46) {
           e.target.text = "";
        }
     })
      
      canvas.renderAll();
    };
  }
}

canvas.add(oText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.1/fabric.min.js"></script>

<canvas id="container" width="780" height="500"></canvas>