如何使用 FabricJS 查詢多邊形物件的平移矩陣?
平移會將物件沿給定方向滑動到固定距離。我們可以透過建立fabric.Polygon的例項來建立多邊形物件。多邊形物件可以透過由一組連線的直線段組成的任何閉合形狀來表示。由於它是 FabricJS 的基本元素之一,因此我們還可以透過應用角度、不透明度等屬性輕鬆地自定義它。
為了找到平移矩陣,我們使用_calcTranslateMatrix()方法。此方法返回一個具有給定值的陣列[ 1, 0, 0, 1, A, B];其中 A 分別是 X 座標和 B 是 Y 座標。
語法
_calcTranslateMatrix(): Array
示例 1:使用 _calcTranslateMatrix 方法
讓我們看一個程式碼示例,說明如何使用_calcTranslateMatrix方法查詢多邊形的平移矩陣。
<!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 _calcTranslateMatrix method</h2>
<p>
You can open console from dev tools and see that the logged output contains the translation 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 _calcTranslateMatrix method
console.log(
"The translation matrix of the polygon instance is: ", polygon._calcTranslateMatrix()
);
</script>
</body>
</html>
示例 2:將 _calcTranslateMatrix 方法與 Scale 方法一起使用
讓我們看一個程式碼示例,瞭解當我們對多邊形物件應用變換時,返回陣列的值是如何受到影響的。在這種情況下,我們使用了 scale 方法,該方法在 x 和 y 方向上對物件進行等比例縮放。縮放會按如下所示轉換矩陣值。
<!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 _calcTranslateMatrix method along with scale method</h2>
<p>
You can open console from dev tools and see that the logged output contains the translation 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 scale method
polygon.scale(2);
// Using _calcTranslateMatrix method
console.log(
"The translation matrix of the polygon instance is: ", polygon._calcTranslateMatrix()
);
</script>
</body>
</html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 查詢多邊形物件的平移矩陣。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP