ADUCJ
ADUCJ

Reputation: 125

Set position for object while adding it to canvas in Fabric.js

I am adding an object to my fabric.js canvas using JavaScript (in a React.JS project), but I don't want it to be rendered in the top left corner every time. I want it so that when I use the canvas.add() function, I can specify the x, y co-ordinates at which I can render the object.

Something like this maybe -

const addObject = (canvas) => {
  img = fabric.Image(img);
  canvas.add(img, 20, 15) //(20,15) represent the x,y co-ordinates of where I want to render img

I just want it so that my object is added to the specified position automatically on calling the addObject() function.

Upvotes: 0

Views: 3045

Answers (1)

Gucal
Gucal

Reputation: 923

You can try using the LEFT and TOP. For example, locating can be done this way. This could be an example for you.

var circle = new fabric.Circle({
left: 20,
top: 15,
radius: 25,
fill: randomColor(),
hasRotatingPoint: true
});
canvas.add(circle)

If you want it to be random, you can use it as follows.

 var circle = new fabric.Circle({
 left: fabric.util.getRandomInt(25, canvas.width - 25),
 top: fabric.util.getRandomInt(25, canvas.height - 25),
 radius: 25,
 fill: randomColor(),
 hasRotatingPoint: true
 });
 canvas.add(circle);

Hopefully it benefits your business.

Upvotes: 1

Related Questions