如何使用 FabricJS 设置矩形选择区域的背景颜色?
在本教程中,我们将学习如何使用 FabricJS 设置矩形选择区域的背景颜色。矩形是 FabricJS 提供的各种形状之一。为了创建矩形,我们需要创建一个 fabric.Rect 类的实例并将其添加到画布上。
当对象被选中时,我们可以更改其尺寸、旋转或操作它。我们可以通过使用 selectionBackgroundColor 属性来更改矩形选择区域的背景颜色。
语法
new fabric.Rect({ selectionBackgroundColor : String }: Object)参数
选项(可选) - 此参数是一个 对象,它为我们的矩形提供了额外的自定义选项。使用此参数,可以更改与对象的 selectionBackgroundColor 属性相关的属性,例如颜色、光标、笔触宽度等等。
选项键
selectionBackgroundColor - 此属性接受一个 字符串 值。分配的值将决定选择区域的背景颜色。
示例 1
未使用 selectionBackgroundColor 属性时的默认颜色
让我们来看一个代码示例,了解当不使用 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>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP