如何使用 FabricJS 查詢多邊形物件的旋轉矩陣?
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表示。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。
為了找到旋轉矩陣,我們使用_calcRotateMatrix()方法。此方法返回一個具有給定值[cosA, sinA, -sinA, cosA, 0, 0]的陣列;其中 A 是以度為單位的旋轉角度。
語法
_calcRotateMatrix(): Array
示例 1:使用 _calcRotateMatrix 方法
讓我們來看一個程式碼示例,說明如何使用_calcRotateMatrix方法查詢多邊形的旋轉矩陣。您可以從開發者工具中開啟控制檯,檢視該陣列僅由 0 和 1 組成,因為它是角度的正弦或餘弦值。
<!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 _calcRotateMatrix method</h2>
<p>
You can open console from dev tools and see that the logged output contains the rotation matrix of the polygon 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);
// Initiating a polygon object
var polygon = new fabric.Polygon(
[
{ x: -20, y: -35 },
{ x: 20, y: -35 },
{ x: 40, y: 0 },
{ x: 20, y: 35 },
{ x: -20, y: 35 },
{ x: -40, y: 0 },
],
{
top: 60,
left: 140,
fill: "red",
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using _calcRotateMatrix method
console.log(
"The rotation matrix of the polygon instance is: ", polygon._calcRotateMatrix()
);
</script>
</body>
</html>
示例 2:結合旋轉方法使用 _calcRotateMatrix 方法
讓我們來看一個程式碼示例,瞭解當我們對多邊形物件應用變換時,返回陣列的值是如何受到影響的。在本例中,我們使用了 rotate 方法,該方法允許我們設定例項的角度。因此,我們的多邊形物件已旋轉 60 度的角度,這反過來又會影響旋轉矩陣的值,因為它是 60 度角的餘弦和正弦值。
<!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 _calcRotateMatrix method along with rotate method</h2>
<p>
You can open console from dev tools and see that the logged output contains the rotation matrix of the polygon 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);
// Initiating a polygon object
var polygon = new fabric.Polygon(
[
{ x: -20, y: -35 },
{ x: 20, y: -35 },
{ x: 40, y: 0 },
{ x: 20, y: 35 },
{ x: -20, y: 35 },
{ x: -40, y: 0 },
],
{
top: 60,
left: 140,
fill: "red",
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using rotate method
polygon.rotate(60);
// Using _calcRotateMatrix method
console.log(
"The rotation matrix of the polygon instance is: ", polygon._calcRotateMatrix()
);
</script>
</body>
</html>
結論
在本教程中,我們使用了兩個簡單的示例來演示如何使用 FabricJS 查詢多邊形物件的旋轉矩陣。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP