我有几个文本对象,我希望以编程方式将我的fabric.js画布集中在一起(而不是必须对它进行眼球和编程。)我正在使用v.1.7.20 of fabric.js。我应该将什么添加到常量中以使每个对象垂直居中?
var canvas = new fabric.Canvas("c");
canvas.setHeight(616);
canvas.setWidth(446);
const text = {
fontSize: 27,
};
// Text that should be centered
canvas.add(new fabric.IText("Line 1", {
...text,
top: 25,
}));
canvas.add(new fabric.IText("Line 2", {
...text,
top: 55,
}));
canvas.add(new fabric.IText("Line 3", {
...text,
top: 85,
}));
canvas.add(new fabric.IText("Line 4", {
...text,
top: 115,
}));
canvas.add(new fabric.IText("Line 5", {
...text,
top: 145,
}));
canvas.add(new fabric.IText("Line 6", {
...text,
top: 175,
}));
canvas.add(new fabric.IText("Line 7", {
...text,
top: 205,
}));
canvas.add(new fabric.IText("Line 8", {
...text,
top: 235,
}));
canvas.add(new fabric.IText("Line 9", {
...text,
top: 265,
}));
canvas.add(new fabric.IText("Line 10", {
...text,
top: 295,
}));

.container {
margin-top: 10px;
}
canvas {
border: 1px solid #dddddd;
margin-top: 10px;
border-radius: 3px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<canvas id="c"></canvas>
&#13;
答案 0 :(得分:1)
使用canvas.centerObjectH(obj)
水平居中对象。这是doc centerObjectH
<强> 样本 强>
var canvas = new fabric.Canvas("c");
canvas.setHeight(616);
canvas.setWidth(446);
const text = {
fontSize: 27
};
// Text that should be centered
canvas.add(new fabric.IText("Line 1", {
...text,
angle:25,
top: 25,
}));
canvas.add(new fabric.IText("Line 2", {
...text,
top: 55,
}));
canvas.add(new fabric.IText("Line 3", {
...text,
top: 85,
}));
canvas.add(new fabric.IText("Line 4", {
...text,
top: 115,
}));
canvas.add(new fabric.IText("Line 5", {
...text,
top: 145,
}));
canvas.add(new fabric.IText("Line 6", {
...text,
top: 175,
}));
canvas.add(new fabric.IText("Line 7", {
...text,
top: 205,
}));
canvas.add(new fabric.IText("Line 8", {
...text,
top: 235,
}));
canvas.add(new fabric.IText("Line 9", {
...text,
top: 265,
}));
canvas.add(new fabric.IText("Line 10", {
...text,
top: 295,
}));
canvas.forEachObject(function(obj){
canvas.centerObjectH(obj)
obj.setCoords();
canvas.renderAll();
})
.container {
margin-top: 10px;
}
canvas {
border: 1px solid #dddddd;
margin-top: 10px;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<canvas id="c"></canvas>
答案 1 :(得分:0)
我能够将以下内容添加到我的常量中。似乎要做的伎俩。如果有人有关于如何改进这一点的想法,我很乐意知道。
left: 223,
originX: center,
originY: center