ps0604
ps0604

Reputation: 1081

Fabricjs: Adding and selecting objects on canvas

This is what I'm trying to achieve in this jsfiddle:

The problem is that when the user clicks on the rect to select it, it also triggers a click on the canvas so another rect is added. How to prevent this to happen?

HTML

<canvas id="c" width="400" height="300"></canvas>

Javascript

var canvas = new fabric.Canvas('c');
canvas.on('mouse:down', function(options) {

    var rect = new fabric.Rect({
       left: options.e.clientX,
       top: options.e.clientY,
       width: 60,
       height: 60,
       fill: 'rgba(255,0,0,0.5)',
   });

   canvas.add(rect);

});

Upvotes: 0

Views: 4256

Answers (1)

ps0604
ps0604

Reputation: 1081

This is how I fixed it, options.target is null if the user clicked on the canvas, not null if the user clicked on an object:

canvas.on('mouse:down', function(options) {

    if (options.target)
       return;

    var rect = new fabric.Rect({
        left: options.e.clientX,
        top: options.e.clientY,
        width: 60,
        height: 60,
        fill: 'rgba(255,0,0,0.5)',
    });
    canvas.add(rect);
});

Upvotes: 1

Related Questions