0

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);
hirazzz
  • 49
  • 2
  • 8

1 Answers1

0

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>
  • sir its still not working. :( is there any other solution to achieve this target? – hirazzz Jan 30 '20 at 17:56
  • then I am not able to understand your question clearly. Like what I am understanding here is that you want to clear the text field by pressing the delete key only. But the above snippet is working like that only so can you please elaborate more what I have missed here – Ashish Bhardwaj Jan 30 '20 at 18:49
  • respected sir the above snippet is not working when i click on delete key. I ran this snippet but not working. – hirazzz Jan 31 '20 at 04:47