gpt4 book ai didi

javascript - 将文本对象设置为在 Canvas 上居中?

转载 作者:行者123 更新时间:2023-12-03 02:51:01 31 4
gpt4 key购买 nike

我有几个文本对象,我希望以编程方式将它们集中在我的fabric.js Canvas 上(而不必逐个查看和编程。)我正在使用fabric.js 的v.1.7.20。我应该在常量中添加什么以使每个对象垂直居中?

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>

最佳答案

使用canvas.centerObjectH(obj)将对象水平居中。这是文档 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>

关于javascript - 将文本对象设置为在 Canvas 上居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47859967/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com