Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...