Reputation: 1243
I have several text objects that I would like to have programmatically centered on my fabric.js canvas (instead of having to eyeball and program each it.) I am using v. 1.7.20 of fabric.js. What should I add to my constant so that each object is centered vertically?
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>
Upvotes: 0
Views: 276
Reputation: 15614
use canvas.centerObjectH(obj)
to center an object horizontally. Here is doc centerObjectH
DEMO
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>
Upvotes: 2
Reputation: 1243
I was able to add the following to my constant. Seemed to do the trick. If anyone has ideas of how to improve this, I'd love to know.
left: 223,
originX: center,
originY: center
Upvotes: 0