0

I created a canvas and I can add objects. How can I remove the item clicked?

var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
  left: 50,
  top: 50,
  fill: 'green',
  width: 40,
  height: 80
});
var circle = new fabric.Circle({
  radius: 20, 
  fill: 'red', 
  left: 100, 
  top: 100
});
canvas.add(rect);
canvas.add(circle);
lilly
  • 111
  • 2
  • 9
  • 2
    [.remove()](http://fabricjs.com/docs/fabric.Collection.html#remove), [Delete multiple Objects at once on a fabric.js canvas in html5](http://stackoverflow.com/questions/11829786/delete-multiple-objects-at-once-on-a-fabric-js-canvas-in-html5) – Andreas Mar 28 '15 at 13:21

2 Answers2

0

Fabric.js provides object:selected event on canvas. You can listen to this event and then remove the item it occurred on. Here's the sample code:

canvas.on('object:selected',function(ev){
    canvas.remove(ev.target);
});

You can read the documentation and look at the jsfiddle i created here: http://jsfiddle.net/yrL4eLsn/1/

Swapnil Jain
  • 1,456
  • 12
  • 19
  • Thanks, can I do it to select two items? – lilly Mar 28 '15 at 14:46
  • Yes. you can use selection:created event which fires when multiple objects are selected. It returns an array of selected objects. You can loop over and remove them as you like. – Swapnil Jain Mar 28 '15 at 14:55
  • I created multiple shapes(rectangle, triangle,circle..) in canvas.I want to select two same shapes and then remove selected two items when I click on second shape? – lilly Mar 28 '15 at 15:15
  • Did not understand what you meant. Can you create a fiddle for your problem? It will be easier. – Swapnil Jain Mar 28 '15 at 15:16
  • I want to click and select first circle then I will click second circle. When I click second circle, circles should be deleted? http://jsfiddle.net/yrL4eLsn/2/ – lilly Mar 28 '15 at 15:34
0

Please refer fabrics readme : fabricjs.com/fabric-intro-part-2/

canvas.on('mouse:down', function(options) {if (options.target){console.log('an object was clicked!',options.target.type);canvas.remove(options.target);}});

Posting code in single line as I am using a cellphone

sujit
  • 2,258
  • 1
  • 15
  • 24