如何使用FabricJS矫正旋转的多边形对象?
我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以用任何由一组连接的直线段组成的封闭形状来表示。因为它是在FabricJS中的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松地自定义它。
我们可以使用straighten方法来矫正旋转的多边形对象。straighten方法通过将对象的旋转角度从当前角度旋转到0、90、180或270度等来矫正对象,具体取决于哪个角度更接近。
语法
straighten(): fabric.Object
示例1:不使用straighten方法传递角度属性值
让我们来看一个代码示例,看看当不使用straighten方法时,我们的多边形对象是什么样的。angle属性以度数设置对象的旋转角度。在这里,我们将角度设置为45度。但是,由于我们没有应用straighten属性,因此旋转角度将保持为45度。
<!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>
Passing the angle property a value without using the straighten method
</h2>
<p>You can see that the polygon has an angle of 45 degrees</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 },
],
{
stroke: "red",
left: 100,
top: 50,
fill: "black",
strokeWidth: 2,
strokeLineJoin: "bevil",
angle: 45,
}
);
// Adding it to the canvas
canvas.add(polygon);
</script>
</body>
</html>
示例2:使用straighten方法
让我们来看一个代码示例,看看当与angle属性一起使用straighten方法时,多边形对象是什么样的。尽管我们将旋转角度设置为45度,但由于我们使用了straighten方法,我们的多边形对象将通过旋转回0度来矫正。
<!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 straighten method</h2>
<p>
You can see that the angle of rotation is 0 degree for the polygon object
</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 },
],
{
stroke: "red",
left: 100,
top: 50,
fill: "black",
strokeWidth: 2,
strokeLineJoin: "bevil",
angle: 45,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the straighten method
polygon.straighten();
</script>
</body>
</html>
结论
在本教程中,我们使用了两个简单的示例来演示如何使用FabricJS矫正旋转的多边形对象。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP