0
votes

On mouse click event, a rectangle is added to the canvas:

    canvas.on({
        'mouse:down': function(options) {
            canvas.add(new fabric.Rect({
                left: options.e.clientX,
                top: options.e.clientY,
                fill: 'red',
                width: 20,
                height: 20
            }));
        }
    });

If I click somewhere else a second rectangle is drawn, and so on. I want the previous rectangle to be removed, for every new mouse click event. I can't use animate() in this case, cause in my application there will be a lot of rectangles drawn and I need to just redraw new rectangles on new places, not moving every one of them.

In native canvas I could just use clearRect() to clear the whole canvas and redraw a new rectangle in the new place. How can I do something like that when using Fabric.js?

1

1 Answers

1
votes

You could create only one rectangle object, and change its left and top position for subsequent mouse down events.

DEMO

var canvas = new fabric.Canvas('canvas',{selection:false});
var rect = new fabric.Rect({
  fill: 'red',
  width: 20,
  height: 20,
  visible:false
});

canvas.add(rect);

canvas.on('mouse:down', function(options) {
  var pointer = canvas.getPointer(options.e);
  rect.set({
    left: pointer.x,
    top: pointer.y,
    visible:true
  });
  canvas.renderAll();
});
canvas{
 border:2px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='canvas' width=500 height=400>