如何使用 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