我們可以通過(guò)創(chuàng)建fabric.Polygon的實(shí)例來(lái)創(chuàng)建一個(gè)Polygon對(duì)象。多邊形對(duì)象的特征可以是由一組連接的直線(xiàn)段組成的任何閉合形狀。由于它是 FabricJS 的基本元素之一,我們還可以通過(guò)應(yīng)用角度、不透明度等屬性來(lái)輕松自定義它。我們使用 skewing 事件來(lái)演示多邊形對(duì)象在被操作時(shí)如何對(duì)用戶(hù)做出反應(yīng)。通過(guò)控制傾斜。
語(yǔ)法
polygon.on("skewing", callbackFunction);
登錄后復(fù)制
示例 1:顯示對(duì)象如何響應(yīng)傾斜事件
讓我們看一個(gè)代碼示例,了解多邊形對(duì)象在使用傾斜事件時(shí)如何反應(yīng)。通過(guò)按 shift 鍵,然后沿水平或垂直方向拖動(dòng)中間控件,可以在水平和垂直方向上傾斜對(duì)象。當(dāng)對(duì)象傾斜時(shí),傾斜事件會(huì)連續(xù)觸發(fā)。
<!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>
登錄后復(fù)制
示例 2:發(fā)生傾斜時(shí)更改填充顏色
讓我們看一個(gè)代碼示例,以了解如何在發(fā)生傾斜事件時(shí)更改填充顏色。我們使用了 set 方法,它是一個(gè)允許我們指定要更改的屬性的設(shè)置器。在這里,每當(dāng)我們傾斜多邊形時(shí),填充顏色就會(huì)變?yōu)椤熬G色”。
<!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>
登錄后復(fù)制
結(jié)論
在本教程中,我們使用兩個(gè)簡(jiǎn)單的示例來(lái)演示如何使用 FabricJS 使多邊形對(duì)象對(duì)傾斜事件做出反應(yīng)。
以上就是如何使用 FabricJS 使多邊形對(duì)象對(duì)傾斜事件做出反應(yīng)?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






