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