如何使用FabricJS设置矩形选择的背景颜色?

在本教程中,我们将学习如何使用 FabricJS 设置矩形选择的背景颜色。矩形是 FabricJS 提供的各种形状之一。为了创建一个矩形,我们必须创建一个 Fabric.Rect 类的实例并将其添加到画布中。
我们可以更改对象的尺寸、旋转它或当它被主动选择时对其进行操作。我们可以使用selectionBackgroundColor属性来更改矩形选择的背景颜色。
语法
new fabric.Rect({ selectionBackgroundColor : String }: Object)参数
选项(可选) - 此参数是一个提供额外自定义的对象到我们的矩形。使用此参数,可以更改与选择背景颜色作为属性的对象相关的颜色、光标、描边宽度和许多其他属性等属性。
选项键
selectionBackgroundColor - 此属性接受 String 值。分配的值将确定选区的背景颜色。
示例 1
未使用 SelectionBackgroundColor 属性时的默认颜色< /strong>
让我们看一个代码示例,以了解在不使用 selectionBackgroundColor 属性时选择内容的显示方式。从这个例子中我们可以看到,选择区域或对象后面的区域没有颜色。
<!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>Default colour when selectionBackgroundColor property is not used</h2>
<p>You can click on the rectangle to see that the selection area has no colour</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 rectangle object
var rect = new fabric.Rect({
left: 155,
top: 70,
width: 170,
height: 70,
fill: "#00b7eb",
stroke: "#ffa089",
strokeWidth: 5,
padding: 50,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>示例 2
将 SelectionBackgroundColor 属性作为键传递
在此示例中,我们为 selectionBackgroundColor 分配一个值财产。在本例中,我们向其传递了十六进制值“#e0ffff”,它是浅青色,因此选择区域看起来是该颜色。
<!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>Passing selectionBackgroundColor property as key</h2>
<p>You can click on the rectangle to see that the selection area now has a light cyan colour</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 rectangle object
var rect = new fabric.Rect({
left: 155,
top: 70,
width: 170,
height: 70,
fill: "#00b7eb",
stroke: "#ffa089",
strokeWidth: 5,
padding: 50,
selectionBackgroundColor: "#e0ffff",
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>
javascript