15

In my fabric application, I'm currently listening for certain key presses such as the delete key, and deleting any selected elements. My method of listening for key presses is:

document.onkeydown = function(e) {
  if (46 === e.keyCode) {
  // 46 is Delete key
  // do stuff to delete selected elements
}

I'm running into a problem though: I have other elements like text boxes on the page, and when typing in a text box, I don't want the delete key to delete any elements.

In this question, there's a method described to attach an event listener to an HTML5 canvas:

canvas.tabIndex = 1000;

allows you to use canvas.addEventListener with keyboard events.

Could I use something similar to this with fabric's canvas?

When I tried it like this,

var CANVAS = new fabric.Canvas('elemID', {selection: false})
CANVAS.tabIndex = 1000;
CANVAS.addEventListener("keydown", myfunc, false);

I get "Uncaught TypeError: undefined is not a function" from Chrome.

2 Answers 2

27

Here's what I've ended up doing: I've got a wrapper div around the canvas used by fabric, and I've added the event listener to this wrapper.

var canvasWrapper = document.getElementById('canvasWrap');
canvasWrapper.tabIndex = 1000;
canvasWrapper.addEventListener("keydown", myfunc, false);

This is working exactly like I want. The delete presses that happen inside a text box aren't picked up by the the listener.

1
  • 1
    This solution works in modern browsers, but not in IE11. But then again, neither does binding the events to the global document. You might as well bind to document, so this dirty hack doesn't really solve anything. In case you want to bind to document, you can simply have your delete function check the canvas objects for the isEditing property. If the user is editing, don't do anything. If not, then delete active objects.
    – Jay
    Jun 6, 2018 at 12:24
0

As Jay suggested "If the user is editing, don't do anything. If not, then delete active objects". If someone is looking complete solution, here it is:

canvas= this.$refs.canvas  

checkDelete(e) {
    if (
      e.keyCode == 46 ||
      e.key == 'Delete' ||
      e.code == 'Delete' ||
      e.key == 'Backspace'
    ) {
      if (this.canvas.getActiveObject()) {
        if (this.canvas.getActiveObject().isEditing) {
          return
        }
        this.deleteObject()
      }
    }
  }
  
  
// Delete object
deleteObject() {
    this.canvasContext.remove(this.canvasContext.getActiveObject())
    this.canvasContext.renderAll()
 }
<div
  tabIndex="1000"
  id="canvasWrapper"
  @keyup="checkDelete($event)"
>
  <canvas ref="canvas"></canvas>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.