如何使用 FabricJS 禁用画布的交互性?
在这篇文章中,我们将学习如何在 FabricJS 中禁用画布的交互性。位于每个对象顶部的交互层是 FabricJS 的独特功能之一。初始化画布后,就可以选择对象、拖动它们或操作组选择。但是,可以通过将 interactive 属性设置为 False 来撤消所有这些操作。
语法
new fabric.Canvas(element: HTMLElement|String, { interactive : Boolean }: Object)参数
element − 此参数是<canvas> 元素本身,可以使用 document.getElementById() 或<canvas> 元素的 ID 获取。FabricJS 画布将在此元素上初始化。
options (可选) − 此参数是一个对象,它为我们的画布提供额外的自定义选项。使用此参数,可以更改与画布相关的许多属性,例如颜色、光标、边框宽度等等,其中 interactive 属性可以让我们决定是否需要一个交互式画布。此属性的默认值为 True。
示例 1
启用 interactive 属性时
启用交互性后,我们可以自由地拖动对象、选择它们并根据需要操作它们。我们可以在下面的代码示例中看到这一点:
<!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>Disabling the interactivity of canvas</h2>
<p>Here you can drag the object and manipulate them freely as we have set the <b>interactive</b> property to True. </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
interactive: true,
});
// Creating an instance of the fabric.Rect class
var obj1 = new fabric.Rect({
left: 170,
top: 90,
width: 60,
height: 80,
fill: "#966fd6",
angle: 90,
});
var obj2 = new fabric.Rect({
left: 200,
top: 120,
width: 60,
height: 80,
fill: "#ffa343",
angle: 56,
});
// Adding it to the canvas
canvas.add(obj1);
canvas.add(obj2);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>示例 2
将 interactive 属性传递给类
让我们来看一个如何禁用画布交互性的代码示例。我们可以将 interactive 属性赋值为 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>Disabling the interactivity of canvas</h2>
<p>Here you cannot select an area around the objects and manipulate them freely, as we have set the <b>interactive</b> property as False. </b>
</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
interactive: false,
});
// Creating an instance of the fabric.Rect class
var obj1 = new fabric.Rect({
left: 170,
top: 90,
width: 60,
height: 80,
fill: "#966fd6",
angle: 90,
});
var obj2 = new fabric.Rect({
left: 200,
top: 120,
width: 60,
height: 80,
fill: "#ffa343",
angle: 56,
});
// Adding it to the canvas
canvas.add(obj1);
canvas.add(obj2);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP