如何使用 FabricJS 建立 Line 物件的字串表示形式?


在本教程中,我們將學習如何使用 FabricJS 建立 Line 物件的字串表示形式。Line 元素是 FabricJS 提供的基本元素之一。它用於建立直線。由於線元素在幾何上是一維的,並且不包含內部,因此它們永遠不會填充。我們可以透過建立 fabric.Line 的例項、指定線的 x 和 y 座標並將其新增到畫布上來建立線物件。為了建立 Line 物件的字串表示形式,我們使用 toString 方法。

語法

 toString(): String 

使用 toString 方法

示例

讓我們看一個程式碼示例,以檢視使用 toString 方法時記錄的輸出。在這種情況下,將返回線例項的字串表示形式。

<!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 toString method</h2> <p> You can open console from dev tools and see that the logged output contains the String representation of the line instance </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 a Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Add it to the canvas canvas.add(line); // Using the toString method console.log( "String representation of the Line instance is: ", line.toString() ); </script> </body> </html>

使用 toString 方法比較兩個不同的元素

示例

讓我們看一個程式碼示例,以瞭解我們如何透過檢視各自的字串表示形式來比較兩個物件。在這裡,我們初始化了一個線例項和一個矩形例項。在對每個例項應用 toString 方法後,我們可以在控制檯中看到它們各自的字串表示形式。

<!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 toString method to compare two different elements</h2> <p> You can open console from dev tools and see that the logged output contains the String representation of the line instance and the rectangle instance </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 a Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Initiate a Rectangle object var rect = new fabric.Rect( { stroke: "red", strokeWidth: 20, width:20, height: 50, left: 400, top: 55 }); // Add them to the canvas canvas.add(line); canvas.add(rect) // Using the toString method console.log( "String representation of the Line instance is: ", line.toString() ); console.log( "String representation of the Rectangle instance is: ", rect.toString() ); </script> </body> </html>

更新於: 2022年10月20日

148 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.