如何使用 FabricJS 設定線條的旋轉角度?
在本教程中,我們將學習如何使用 FabricJS 設定線條的旋轉角度。線條元素是 FabricJS 提供的基本元素之一。它用於建立直線。由於線條元素在幾何上是一維的並且不包含內部,因此它們永遠不會被填充。
我們可以透過建立fabric.Line的例項,指定線條的 x 和 y 座標並將其新增到畫布上來建立線條物件。centeredRotation 屬性允許我們使用線條物件的中心點作為變換的原點。
語法
new fabric.Line( points: Array , { angle: Number, centeredRotation: Boolean }: Object)
引數
points − 此引數接受一個陣列點,它確定 (x1, y1) 和 (x2, y2) 值,分別為線條起點和終點的 x 軸和 y 軸座標。
options(可選)− 此引數是一個物件,它為我們的物件提供額外的自定義。使用此引數,可以更改與線條物件相關的原點、筆劃寬度和許多其他屬性,其中angle和centeredRotation是屬性。
選項鍵
angle − 此屬性接受一個數字,以度為單位指定線條物件的旋轉角度。
centeredRotation − 該屬性接受一個布林值,它確定線條物件的中心是否為變換的原點。
將angle作為鍵傳遞自定義值,並停用線條的中心旋轉
示例
讓我們看一個程式碼示例,以設定 FabricJS 中線條的旋轉角度。負角度表示逆時針方向,而正角度表示順時針方向。由於我們將centeredRotation分配了一個假值,因此線條物件在使用其角點作為旋轉中心時將旋轉。
<!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>Passing angle as key with a custom value and disabling the centered rotation for the Line</h2> <p> You can select and rotate the line object to verify that it uses its corner point as the center of rotation </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, centeredRotation: false, angle: 15, }); // Add it to the canvas canvas.add(line); </script> </body> </html>
啟用線條物件的中心旋轉
示例
從這個例子中我們可以看到,透過將centeredRotation屬性設定為 true,我們的線條物件現在使用其中心作為旋轉中心。在 1.3.4 版本之前,centeredScaling和centeredRotation包含在一個名為 centerTransform 的單個屬性中。
<!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>Enabling centered rotation for the line object</h2> <p> You can select and rotate the line object to verify that it now uses its center as center of rotation </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, centeredRotation: true, angle: 15, }); // Add it to the canvas canvas.add(line); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP