如何使用 FabricJS 使多边形对象对旋转事件做出反应?
我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以由任何由一组连接的直线段组成的闭合形状来表征。由于它是 FabricJS 的基本元素之一,因此我们还可以通过应用角度、不透明度等属性轻松地自定义它。我们使用rotating事件来演示如何使多边形对象对通过控件进行旋转做出反应。
语法
polygon.on(“rotating”, callbackFunction);
示例 1:显示对象如何对旋转事件做出反应
让我们来看一个代码示例,说明如何使多边形对象对rotating事件做出反应。在这种情况下,一旦我们点击多边形对象并通过中间旋转控件旋转它,我们就会看到记录的输出。这是因为在对象旋转时,旋转事件会连续触发。
<!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 rotating event</h2>
<p>You can rotate the object to see the callback function fired</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 rotating event
polygon.on("rotating", () => {
canvas.renderAll();
console.log("The polygon object is rotating");
});
</script>
</body>
</html>
示例 2:旋转发生时更改填充颜色
让我们来看一个代码示例,了解如何在rotating事件发生时更改填充颜色。我们可以使用对象的中间旋转 (mtr) 控件来旋转画布上的对象。在这里,当我们使用其 mtr 控件旋转多边形对象时,填充颜色将更改为“绿色”。
<!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 rotate happens</h2>
<p>
You can see that the fill colour changes when the polygon is rotated
</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 rotating event
polygon.on("rotating", () => {
polygon.set("fill", "green")
canvas.renderAll();
});
</script>
</body>
</html>
结论
在本教程中,我们使用了两个简单的示例来演示如何使用 FabricJS 使多边形对象对旋转事件做出反应。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP