如何使用 FabricJS 設定文字的旋轉角度?
在本教程中,我們將使用 FabricJS 設定文字的旋轉角度。我們可以透過新增 fabric.Text 的例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字裝飾、行高,這些可以透過 textAlign、underline 和 lineHeight 屬性分別獲取。FabricJS 中的 angle 屬性定義了物件的 2D 旋轉角度。我們還有一個 centeredRotation 屬性,它允許我們使用文字物件的中心點作為變換的原點。
語法
new fabric.Text(text: String , { angle: Number, centeredRotation: Boolean }: Object)
引數
text − 此引數接受一個字串,即我們要顯示的文字字串。
options(可選) − 此引數是一個物件,它為我們的文字提供額外的自定義。使用此引數可以更改與文字物件相關的顏色、游標、筆觸寬度以及許多其他屬性,其中 angle 和 centeredRotation 是屬性。
選項鍵
angle − 此屬性接受一個數字,它以度為單位指定文字物件的旋轉角度。
centeredRotation − 此屬性接受一個布林值,它確定文字物件的中心是否為變換的原點。
示例 1
將 angle 作為鍵傳遞自定義值,並停用文字的居中旋轉
讓我們看一個程式碼示例,以設定 FabricJS 中文字的旋轉角度。負角度表示逆時針方向,正角度表示順時針方向。由於我們將 centeredRotation 賦值為 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>Passing angle as key with a custom value and disabling the centered rotation for the Text</h2> <p>You can select and rotate the text 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 text object var text = new fabric.Text("Add Sample Text Here", { width: 200, top: 70, left: 60, centeredRotation: false, angle: 15, }); // Add it to the canvas canvas.add(text); </script> </body> </html>
示例 2
啟用文字物件的居中旋轉
從這個例子中我們可以看到,透過將 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 text object</h2> <p>You can select and rotate the text 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 text object var text = new fabric.Text("Add Sample Text Here", { width: 200, top: 70, left: 110, centeredRotation: true, angle: 15, }); // Add it to the canvas canvas.add(text); </script> </body> </html>
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP