2016-01-14

Fabric.js double click event on items (JavaScript)

Fabric.js is one of the greatest JavaScript libraries to deal with <Canvas> element. It is free, simple and intuitive to use. Out-of-the box functionalities like item handles, SVG-to-Canvas and Canvas-to-SVG parser make the difference compared to other similar libraries.


// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c');

// create a rectangle object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20
});

// "add" rectangle onto canvas
canvas.add(rect);

While I was working on my latest project I needed doubleclick functionality which is not out available with core Fabric.js. Problem? No really, since there is extension available at https://github.com/mazong1123/fabric.ext. Now, instead of creating new Canvas object use CanvasEx.
<script src="scripts/fabric.canvasex.js"></script>
  var canvas = new fabric.CanvasEx('c');
  canvas.on('mouse:dblclick', function (options) {
    console.log('mouse:dblclick');
  });

  var rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: 'red',
    width: 300,
    height: 300
  });

  rect.on('object:dblclick', function (options) {
    console.log('object:dblclick');
  });

  canvas.add(rect);

1 comment: