Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric js how to add text on 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

like image 899
Rai Avatar asked Sep 16 '16 09:09

Rai


1 Answers

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>
like image 117
alessandro Avatar answered Oct 01 '22 04:10

alessandro