Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 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.

question from:https://stackoverflow.com/questions/65560231/set-position-for-object-while-adding-it-to-canvas-in-fabric-js

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

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...