如何使用 FabricJS 查找 Polygon 对象的平移矩阵?
fabricjsjavascripthtml5 canvas更新于 2024/9/14 19:56:17
平移将对象沿给定方向滑动到固定距离。我们可以通过创建 fabric.Polygon 实例来创建 Polygon 对象。多边形对象的特征是任何由一组连接的直线段组成的封闭形状。由于它是 FabricJS 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松地对其进行自定义。
为了找到平移矩阵,我们使用 _calcTranslateMatrix() 方法。此方法返回具有给定值 [ 1, 0, 0, 1, A, B] 的数组;其中 A 是 X 坐标,B 是 Y 坐标。
语法
_calcTranslateMatrix():数组
示例 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>
// 启动一个canvas实例
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// 初始化多边形对象
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",
}
);
// 将其添加到画布
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>
// 启动一个canvas实例
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// 初始化多边形对象
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",
}
);
// 将其添加到画布
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 对象的平移矩阵。
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

