平移將物件沿著給定方向滑動到固定距離。我們可以透過建立fabric.Polygon的實例來建立一個Polygon物件。多邊形物件的特徵可以是由一組連接的直線段組成的任何閉合形狀。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性輕鬆自訂它。
為了找到平移矩陣,我們使用_calcTranslateMatrix()方法。此方法傳回一個具有給定值的陣列 [ 1, 0, 0, 1, A, B];其中 A 是 X 座標,B 是 Y 座標。
_calcTranslateMatrix(): Array
讓我們來看一個程式碼範例,了解如何使用 _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>
讓我們看一個程式碼範例,以了解當我們對多邊形物件應用變換時,傳回數組的值是如何受到影響的。在本例中,我們使用了縮放方法,該方法在 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 來尋找 Polygon 物件的平移矩陣。
以上是如何使用 FabricJS 找出 Polygon 物件的平移矩陣?的詳細內容。更多資訊請關注PHP中文網其他相關文章!