Rai*_*Rai 5 javascript fabricjs
我需要在 img 对象上添加文本我的代码
$("#c2").click(function(){
fabric.Image.fromURL('/some/link/free_circle_2.png', function(img){
img.setWidth(50);
img.setHeight(50);
canvas.add(img);
});
});
Run Code Online (Sandbox Code Playgroud)
添加图像后,我需要添加以该图像为中心的数字。我知道我需要更改canvas.add(img);为canvas.sendToBack(img);但如何添加保持图像位置的文本
要根据图像的位置保持文本的位置,您应该使用Group,如下所示:
var group = new fabric.Group([img, text], {
left: 150,
top: 100,
});
Run Code Online (Sandbox Code Playgroud)
然后将您的文本放在图像的中间,因为您的文本相对于组的位置,您应该执行以下操作:
text.set("top", (img.getBoundingRect().height / 2) - (text.width / 2));
text.set("left", (img.getBoundingRect().width / 2) - (text.height / 2));
Run Code Online (Sandbox Code Playgroud)
其中getBoundingRect返回对象边界矩形的坐标(左、上、宽、高)
然后,
如果满足您的需要,请尝试以下可运行示例:
var group = new fabric.Group([img, text], {
left: 150,
top: 100,
});
Run Code Online (Sandbox Code Playgroud)
text.set("top", (img.getBoundingRect().height / 2) - (text.width / 2));
text.set("left", (img.getBoundingRect().width / 2) - (text.height / 2));
Run Code Online (Sandbox Code Playgroud)
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);
});
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4559 次 |
| 最近记录: |