admin管理员组

文章数量:1290978

I need to add text on img object my code

$("#c2").click(function(){
fabric.Image.fromURL('/some/link/free_circle_2.png', function(img){
    img.setWidth(50);
    img.setHeight(50);
    canvas.add(img);

  });
});

after adding image i need add number centered of this image. I know i need to change canvas.add(img); to canvas.sendToBack(img); but how to add text keeping the position of the image

I need to add text on img object my code

$("#c2").click(function(){
fabric.Image.fromURL('/some/link/free_circle_2.png', function(img){
    img.setWidth(50);
    img.setHeight(50);
    canvas.add(img);

  });
});

after adding image i need add number centered of this image. I know i need to change canvas.add(img); to canvas.sendToBack(img); but how to add text keeping the position of the image

Share Improve this question edited Sep 16, 2016 at 22:52 Morgan 4,13130 silver badges35 bronze badges asked Sep 16, 2016 at 9:29 RaiRai 1935 silver badges15 bronze badges 2
  • put image and text inside a group – invernomuto Commented Sep 16, 2016 at 11:25
  • @Infer-on ok, but question was adding text after add image on canvas (after adding image i need add number centered of this image) – Rai Commented Sep 16, 2016 at 15:29
Add a ment  | 

1 Answer 1

Reset to default 10

To keep the position of your text, based upon the position of your image, you should use a Group, like this:

var group = new fabric.Group([img, text], {
          left: 150,
          top: 100,

        });

Then to place your text in the middle of your image, since the position of your text its relative to the group, you should do something like this:

text.set("top", (img.getBoundingRect().height / 2) - (text.width / 2));
text.set("left", (img.getBoundingRect().width / 2) - (text.height / 2));

Where getBoundingRect returns coordinates of object's bounding rectangle (left, top, width, height)

then,

Try yourself the following runnable example if it meets your needs:

var canvas = new fabric.Canvas('c');

$("#c2").click(function() {
  fabric.Image.fromURL('https://upload.wikimedia/wikipedia/mons/2/25/Herma_of_Plato_-_0049MC.jpg', function(img) {

    img.setWidth(100);
    img.setHeight(100);

    var text = new fabric.Text("01", {
      fontFamily: 'Comic Sans',
      fontSize: 20
    });

    text.set("top", (img.getBoundingRectHeight() / 2) - (text.width / 2));
    text.set("left", (img.getBoundingRectWidth() / 2) - (text.height / 2));
    var group = new fabric.Group([img, text], {
      left: 100,
      top: 25,

    });

    canvas.add(group);
  });
});
canvas {
  border: 1px dashed #333;
}
<script src="https://cdnjs.cloudflare./ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='c' width=300 height=150 '></canvas>
<br>
<button id='c2'>ok</button>

本文标签: javascriptFabric js how to add text on imageStack Overflow