Venk
Venk

Reputation: 230

FabricJS check if double clicked on a text object with _onDoubleClick?

I've been playing around with my fabric.min.js file recently and I came across this:

_onDoubleClick: function(t) {
    this._cacheTransformEventData(t), this._handleEvent(t, "dblclick"), this._resetTransformEventData(t);
},

So instinctively, I decided to see what it did by adding an alert() function. As expected, it just showed the alert whenever the mouse was double-clicked.

What I'm trying to do is make a different alert for the object type, if that makes sense.

_onDoubleClick: function(t) {
    this._cacheTransformEventData(t), this._handleEvent(t, "dblclick"), this._resetTransformEventData(t);
    // This code doesn't work
    if (t.type === 'text') alert("You double-clicked on a text box")
    else alert("You double-clicked on a prop")
},

Basically, I just want to check if a text box was double-clicked or not, how can I do this?

Upvotes: 1

Views: 1516

Answers (1)

Adam M.
Adam M.

Reputation: 1088

Changing the library itself is normally never a good idea. FabricJS uses that function to give as a nice events interface:

http://fabricjs.com/events http://fabricjs.com/fabric-intro-part-2#events

Please see the example below to see how can you achieve what you are looking for, without changing the core library.

var canvas = new fabric.Canvas(document.querySelector('canvas'))
var textBox = new fabric.Text('Lorem Ipsum Dolor', { left: 20, top: 20 })
var circle = new fabric.Circle({ radius: 30, fill: 'green', left: 130, top: 75 })

// Listen on the text object
textBox.on('mousedblclick', function() {
  console.log('Text object was double clicked')
})

// Listen on the circle object
circle.on('mousedblclick', function() {
  console.log('Circle object was double clicked')
})

// Listen for any double click events on the canvas
canvas.on('mouse:dblclick', function(e) {
  if (e.target.type === 'circle') {
    console.log('The clicked object was a circle')
  } else if (e.target.type === 'text') {
    console.log('The clicked object was a text')
  }
})

canvas.add(textBox)
canvas.add(circle)

canvas.renderAll()
body {
    background: #f0f0f0;
    padding: 0;
    margin: 0;
}
canvas {
    border: 1px solid lightgray;
}
div {
    margin: 0.5em 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.3/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<canvas width="400" height="150"></canvas>

Upvotes: 1

Related Questions