如何使用 FabricJS 判断给定对象是否为 Polyline 实例?
我们可以通过创建 fabric.Polyline 的实例来创建 Polyline 对象。Polyline 对象可以由一组连接的直线段来表征。由于它是 FabricJS 的基本元素之一,因此我们也可以通过应用角度、不透明度等属性轻松自定义它。
为了判断给定对象是否为 Polyline 实例,我们使用 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 polyline object
var polyline = new fabric.Polyline(
[
{ 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(polyline);
// Using isType method
console.log(
"Is the specified type identical to a polyline instance? : ",
polyline.isType("polyline")
);
</script>
</body>
</html>
示例 2:使用带有不同值的 isType 方法
在本例中,我们使用了 isType 来检查指定的圆形类型是否与 Polyline 实例相同。这里返回 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 polyline object
var polyline = new fabric.Polyline(
[
{ 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(polyline);
// Using isType method
console.log(
"Is the specified type identical to a polyline instance? : ",
polyline.isType("circle")
);
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP