FabricJS – 如何識別給定物件是否為多邊形例項?
我們可以透過建立fabric.Polygon例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表示。由於它是 FabricJS 的基本元素之一,我們還可以透過應用角度、不透明度等屬性輕鬆自定義它。
為了識別給定物件是否為多邊形例項,我們使用isType方法。此方法檢查物件是否為指定的型別,並根據該型別返回true或false值。
語法
isType(type: String): Boolean
引數
type − 此引數接受一個字串,該字串指定我們要檢查的型別。
示例 1:使用 isType 方法
讓我們來看一個程式碼示例,以檢視使用isType方法時的日誌輸出。isType方法返回 true 或 false 值,具體取決於例項的型別是否與我們想要檢查的型別匹配。在本例中,由於型別匹配,因此返回 true 值。
<!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 isType method</h2>
<p>You can open console from dev tools and see the logged output</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,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using isType method
console.log(
"Is the specified type identical to a polygon instance? : ",
polygon.isType("polygon")
);
</script>
</body>
</html>
示例 2:使用帶有不同值的 isType 方法
在這個例子中,我們使用了isType來檢查指定的圓形型別是否與多邊形例項相同。在這裡,返回 false 值,因為它們並不相同。
<!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 isType method with a different value</h2>
<p>
You can open console from dev tools and see that the logged output contains a false value
</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,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using isType method
console.log(
"Is the specified type identical to a polygon instance? : ", polygon.isType("circle")
);
</script>
</body>
</html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 識別給定物件是否為多邊形例項。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP