StAR_161
StAR_161

Reputation: 658

How do I create multiple shapes with Fabric.js?

I want to be able to create multiple rectangles on the canvas using double clicks. However, I'm able to create only one rectangle. Also, is there is a way to add an ID to every rectangle that is created? I want to be able to access any rectangle I want at any time and change its properties.

var i=0;

function drawRectangle() {
   if (rectClickToggle) {
          getMouse(event);
          var canvas = new fabric.Canvas('drawArea');
          canvas.add(new fabric.Rect({width:20,height:20,fill:'#f55',top:my,left:mx}));
          canvas.item(i).set({borderColor:'red',cornerColor:'green',cornerSize:6,transparentCorners: false});
          canvas.setActiveObject(canvas.item(i));   
          i++;
       }
  }

 drawArea.ondblclick = drawRectangle;

Upvotes: 0

Views: 1834

Answers (1)

Cory Silva
Cory Silva

Reputation: 2811

Every time you call the drawRectangle function you are redefining the canvas. Try moving that code outside the drawRectangle function.


Edit - for drawing many rectangles.

var canvas = new fabric.StaticCanvas('canvas-ele');
canvas.setHeight(300);
canvas.setWidth(300);
var drawRect = function(e) {
    canvas.add(new fabric.Rect({
            left: e.x - 10,
            top: e.y - 10,
            fill: 'rgba(100,0,0,0.3)',
            width: 72,
            height: 72,
            stroke: 'black'
        })
    );
};
var canvasEle = document.getElementById('canvas-ele');
canvasEle.ondblclick = function (e) {
    drawRect(e);
};
canvas.renderAll();

Try the fiddle http://jsfiddle.net/coryasilva/Y5fu5/

***As a side note I do not recommend using a double click; it makes for a poor user experience)


Edit #2

I understand better now. How does this work?

http://jsfiddle.net/Y5fu5/3/

Upvotes: 2

Related Questions