Search code examples
javascriptfabricjs

fabric.js-adding an event handler to an object doesn't work


When I click the rect, the console only prints click the canvas instead of click the rect. Is there any solution?

var canvas = window._canvas = new fabric.Canvas('c');

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

canvas.add(rect);


rect.on('mouse:down', function(options){
    console.log("click the rect");
    })

canvas.on('mouse:down',function(options){
    console.log("click the canvas");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
<canvas id="c" width="600" height="600"></canvas>


Solution

  • 'mouse:down' is an event type of fabric.Canvas, but not an event of fabric.Rect.

    You can check by experimenting with the event on the official website at the link below. http://fabricjs.com/events

    I'm not sure what exactly the square will do when you click on it. However, if you want to run a function when a rectangle is selected or deselected, write the code as follows.

    var canvas = window._canvas = new fabric.Canvas('c');
    
    var rect = new fabric.Rect({
        left: 100,
        top: 100,
        fill: 'red',
        width: 100,
        height: 100
      });
    
    canvas.add(rect);
    
    rect.on('selected', function(options){
        console.log("select the rect");
    })
    
    rect.on('deselected', function(options){
        console.log("deselect the rect");
    })
    
    canvas.on('mouse:down',function(options){
        console.log("click the canvas");
    })
    

    I hope it was helpful to you. Thank you :)