LVSAVAJE
LVSAVAJE

Reputation: 59

FabricJS layers

Initially, an object (fabric.Circle) is added to my canvas.

var canvas = new fabric.Canvas('myCanvas');
var circle = new fabric.Circle ({
    radius: 100,
    fill: 'white',
    stroke: 'black',
    originX: 'center',
    originY: 'center'
});
canvas.add(circle);

Now if I use a button to add another object to my canvas, the previous one disappears. I reckon it adds the new object on top of the previous layer.

I don't want that. Is there any way to keep adding objects to the current layer without losing the FabricJS's functionalities?

Edit: The button and its corresponding function are as follows:

<button onclick="addArrowToCanvas()">Add Circle</button>
<script>
                function addArrowToCanvas(){
                    var canvas = new fabric.Canvas('myCanvas');
                    var circle = new fabric.Circle ({
                        radius: 100,
                        fill: 'white',
                        stroke: 'black',
                        originX: 'center',
                        originY: 'center'
                    });
                    canvas.add(circle);
                }
            </script>

Upvotes: 1

Views: 1652

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

Yes, that indeed adds the other object on top of the previous one, as you didn't specify the position for the object when creating it.

You need to set different positions (top, left) for each individual object as per your need, so that they don't overlap each other.

ᴅᴇᴍᴏ

var canvas = new fabric.Canvas('myCanvas');
var circle = new fabric.Circle({
   top: 50,  //<-- set this
   left: 50,  //<-- set this
   radius: 30,
   fill: 'white',
   stroke: 'black',
   originX: 'center',
   originY: 'center'
});
canvas.add(circle);

function addRect() {
   var rect = new fabric.Rect({
      top: 120,  //<-- set this
      left: 120,  //<-- set this
      width: 60,
      height: 60,
      fill: 'white',
      stroke: 'black',
      originX: 'center',
      originY: 'center'
   })
   canvas.add(rect);
}
body{margin:10px 0 0 0;overflow:hidden}canvas {border: 1px solid #ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="myCanvas" width="180" height="180"></canvas>
<button onclick="addRect()">Add Rectangle</button>

Upvotes: 2

Related Questions