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
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.org/wikipedia/commons/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.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='c' width=300 height=150 '></canvas>
<br>
<button id='c2'>ok</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With