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
- 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
1 Answer
Reset to default 10To 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
版权声明:本文标题:javascript - Fabric js how to add text on image - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741512611a2382694.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论