如何使用 FabricJS 使多边形对象对倾斜事件做出反应?
我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以由任何由一组连接的直线段组成的闭合形状来表示。由于它是 FabricJS 的基本元素之一,因此我们也可以通过应用角度、不透明度等属性轻松地对其进行自定义。我们使用倾斜事件来演示多边形对象在通过控件进行倾斜时如何对用户做出反应。
语法
polygon.on("skewing", callbackFunction);
示例 1:显示对象如何对倾斜事件做出反应
让我们来看一个代码示例,说明多边形对象在使用倾斜事件时的反应。通过按住Shift 键,然后沿水平或垂直方向拖动中间控件,可以沿水平和垂直方向倾斜对象。在对象被倾斜时,会连续触发倾斜事件。
<!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>Displaying how the object reacts to the skewing event</h2>
<p>
You can keep skewing the object while the console from dev tools is open to 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);
// Initiate a polygon instance
var polygon = new fabric.Polygon(
[
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
{ x: 500, y: 20 },
],
{
fill: "red",
stroke: "blue",
strokeWidth: 2,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the skewing event
polygon.on("skewing", () => {
canvas.renderAll();
console.log("The polygon object is being skewed");
});
</script>
</body>
</html>
示例 2:倾斜发生时更改填充颜色
让我们来看一个代码示例,了解如何在倾斜事件发生时更改填充颜色。我们使用了set方法,这是一个setter,它允许我们指定要更改的属性。在这里,每当我们倾斜多边形时,填充颜色都会更改为“绿色”。
<!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>Changing the fill colour when skew happens</h2>
<p>
You can see that the fill colour changes when the polygon is skewed
</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a polygon instance
var polygon = new fabric.Polygon(
[
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
{ x: 500, y: 20 },
],
{
fill: "red",
stroke: "blue",
strokeWidth: 2,
objectCaching: false,
top: 50,
left: 30,
scaleX: 0.5,
scaleY: 0.5
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the skewing event
polygon.on("skewing", () => {
polygon.set("fill", "green")
canvas.renderAll();
});
</script>
</body>
</html>
结论
在本教程中,我们使用两个简单的示例来演示如何使用 FabricJS 使多边形对象对倾斜事件做出反应。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP