WhiteHotLoveTiger
WhiteHotLoveTiger

Reputation: 2228

fabric.js canvas listen for keyboard events?

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.

Upvotes: 15

Views: 13368

Answers (2)

Yogesh Yadav
Yogesh Yadav

Reputation: 863

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>

Upvotes: 0

WhiteHotLoveTiger
WhiteHotLoveTiger

Reputation: 2228

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.

Upvotes: 27

Related Questions