如何在使用 FabricJS 的 IText 中,相對於畫布的當前視口水平居中物件?


在本教程中,我們將學習如何在使用 FabricJS 的 IText 中,相對於畫布的當前視口水平居中物件。IText 類是在 FabricJS 1.4 版本中引入的,擴充套件了 fabric.Text,用於建立 IText 例項。IText 例項使我們能夠在無需額外配置的情況下選擇、剪下、貼上或新增新文字。它還支援各種鍵盤組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中沒有提供。

但是,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說是不正確的,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 **viewportCenterH** 方法相對於畫布的當前視口水平居中物件。

語法

viewportCenterH(): fabric.Object

示例 1

IText 物件的預設外觀

讓我們看一個程式碼示例,看看在不使用 viewportCenterH 方法時 IText 物件是什麼樣子。在這種情況下,IText 物件不會在畫布上水平居中。

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Default appearance of the IText object</h2> <p>You can see that the itext object has not been centered horizontally with respect to the current viewport of canvas</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 50, top: 70, fill: "red", }); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

使用 viewportCenterH 方法

讓我們看一個程式碼示例,看看使用 viewportCenterH 方法時 IText 物件是什麼樣子。在這種情況下,我們的 IText 物件將相對於畫布的當前視口水平居中。

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Using the viewportCenterH method</h2> <p>You can see that the itext object has been centered horizontally with respect to the current viewport of canvas</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 50, top: 70, fill: "red", }); // Add it to the canvas canvas.add(itext); // Using the viewportCenterH method itext.viewportCenterH(); </script> </body> </html>

更新於: 2022-09-12

124 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.