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