如何使用 FabricJS 檢查 IText 物件是否具有特定的樣式屬性?
在本教程中,我們將學習如何使用 FabricJS 檢查 IText 物件是否具有特定的樣式屬性。IText 類是在 FabricJS 1.4 版本中引入的,它擴充套件了 fabric.Text,用於建立 IText 例項。IText 例項使我們能夠自由地選擇、剪下、貼上或新增新文字,無需額外的配置。它還支援各種按鍵組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中並未提供。
然而,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說並不適用,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 styleHas 方法來檢查 IText 物件是否具有特定的樣式屬性。
語法
styleHas(property: String, lineIndex: Number): Boolean
引數
property − 此引數接受一個字串,表示要檢查的屬性。
lineIndex − 此引數接受一個數字,表示要檢查樣式的索引。
示例 1
使用 styleHas 方法
讓我們看一個程式碼示例,瞭解使用 styleHas 方法時的日誌輸出。在本例中,我們正在檢查第 0 行字元中是否存在 fill 屬性。由於該值存在,控制檯中將返回 true 值。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <scrip src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Using the styleHas method</h2> <p>You can open console from dev tools and see that a true value is being displayed in the console</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
Lorem ipsum ", { width: 300, left: 50, top: 70, fontSize: 30, fill: "red", backgroundColor: "#fedad2", angle: 25, styles: { 0: { 1: { fill: "blue", fontStyle: "bold", }, }, }, }); // Using the styleHas method console.log("Is fill property present? : ", itext.styleHas("fill", 0)); // Add it to the canvas canvas.add(itext); </script> </body> </html>
示例 2
使用 styleHas 方法檢查不存在的值
讓我們看一個程式碼示例,瞭解使用 styleHas 方法檢查不存在的值時的日誌輸出。在本例中,我們正在檢查第 0 行字元中是否存在 fontSize 屬性。由於它不存在,因此將返回 false 值。
<!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 styleHas method to check for a value that is not present</h2> <p>You can open console from dev tools and see that a false value is being displayed in the console</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
Lorem ipsum ", { width: 300, left: 50, top: 70, fontSize: 30, fill: "red", backgroundColor: "#fedad2", angle: 25, styles: { 0: { 1: { fill: "blue", fontStyle: "bold", }, }, }, }); // Using the styleHas method console.log( "Is font size property present? : ", itext.styleHas("fontSize", 0) ); // Add it to the canvas canvas.add(itext); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP