Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
WhiteHotLoveTiger Avatar asked Jul 10 '14 19:07

WhiteHotLoveTiger


1 Answers

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.

like image 99
WhiteHotLoveTiger Avatar answered Oct 18 '22 20:10

WhiteHotLoveTiger