FabricJS – 找到代表多边形对象当前变换的变换矩阵
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。为了找到代表当前变换的变换矩阵,我们使用calcOwnMatrix方法。
语法
calcOwnMatrix(): Array
例1:使用calcOwnMatrix方法
让我们看一个代码例子,通过使用calcOwnMatrix方法,我们可以找到代表一个多边形当前变换的变换矩阵。你可以从开发工具中打开控制台,看到显示的是数组的值。
<!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 calcOwnMatrix method</h2>
<p>
You can open console from dev tools and see that the logged output contains the transform 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: 200, y: 10 },
{ x: 250, y: 50 },
{ x: 250, y: 180 },
{ x: 150, y: 180 },
{ x: 150, y: 50 },
{ x: 200, y: 10 },
],
{
fill: "green",
stroke: "blue",
strokeWidth: 20,
skewX: 15,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using calcOwnMatrix method
console.log(
"The transform matrix which represents current transformation of the polygon instance is: ",
polygon.calcOwnMatrix()
);
</script>
</body>
</html>
例2:使用calcOwnMatrix方法和ScaleX属性
让我们看一个代码例子,了解当我们对多边形对象应用水平缩放时,返回的数组的值是如何被影响的。这里,我们给scaleX属性传递了一个2的值,这确保我们的多边形对象在水平方向上被缩放了2。我们还可以在控制台中看到,返回数组的第0个索引值已经改变。这是因为第0个索引标志着scaleX值。
<!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 calcOwnMatrix method along with scaleX property</h2>
<p>
You can open console from dev tools and see that the logged output has changed
</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: 200, y: 10 },
{ x: 250, y: 50 },
{ x: 250, y: 180 },
{ x: 150, y: 180 },
{ x: 150, y: 50 },
{ x: 200, y: 10 },
],
{
fill: "green",
stroke: "blue",
strokeWidth: 20,
skewX: 15,
scaleX: 2,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using calcOwnMatrix method
console.log(
"The transform matrix which represents current transformation of the polygon instance is: ",
polygon.calcOwnMatrix()
);
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS找到代表多边形对象当前变换的变换矩阵。