如何使用 FabricJS 查找多边形对象的旋转矩阵?


我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以由任何由一组连接的直线段组成的封闭形状来表示。由于它是 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松地对其进行自定义。

为了找到旋转矩阵,我们使用_calcRotateMatrix()方法。此方法返回一个具有给定值[cosA, sinA, -sinA, cosA, 0, 0]的数组;其中 A 是以度为单位的旋转角度。

语法

_calcRotateMatrix(): Array

示例 1:使用 _calcRotateMatrix 方法

让我们来看一个代码示例,说明如何使用_calcRotateMatrix方法查找多边形的旋转矩阵。您可以从开发者工具中打开控制台,查看该数组仅由 0 和 1 组成,因为它是角度的正弦或余弦值。

Open Compiler
<!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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2:结合旋转方法使用 _calcRotateMatrix 方法

让我们来看一个代码示例,了解当我们对多边形对象应用变换时,返回数组的值是如何受到影响的。在本例中,我们使用了 rotate 方法,该方法允许我们设置实例的角度。因此,我们的多边形对象已旋转 60 度的角度,这反过来又会影响旋转矩阵的值,因为它是 60 度角的余弦和正弦值。

Open Compiler
<!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 查找多边形对象的旋转矩阵。

更新于:2023年1月2日

215 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告