如何使用 FabricJS 设置画布上选择区域的颜色?
在本文中,我们将学习如何使用 FabricJS 设置画布上选择区域的颜色。我们可以使用 selectionColor 属性调整颜色。
语法
new fabric.Canvas(element: HTMLElement|String, { selectionColor: String }: Object)参数
element − 此参数是<canvas> 元素本身,可以使用 document.getElementById() 或 <canvas> 元素的 id 获取。FabricJS 画布将在此元素上初始化。
options (可选) − 此参数是一个对象,它为我们的画布提供了额外的自定义选项。使用此参数,可以更改与画布相关的颜色、光标、边框宽度等许多其他属性,其中 selectionColor 是一个属性,我们可以用它来指示选择的颜色。selectionColor 的默认值为 rgba(100,100,255,0.3)。
示例 1
将 selectionColor 键传递给类
selectionColor 属性接受一个字符串,该字符串确定选择的颜色。我们可以使用 RGBA 值,它代表:红色、蓝色、绿色和 alpha。alpha 参数指定颜色的不透明度。让我们看一个代码示例,说明如何使用 FabricJS 设置画布中选择区域的颜色。
<!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>Setting the color of a selection area using FabricJs</h2>
<p>Select an area around the object to see the color of the selection area.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
selectionColor: "rgba(0,0,0,0.4)",
});
// Creating an instance of the fabric.Rect class
var rect = new fabric.Rect({
left: 170,
top: 90,
width: 60,
height: 80,
fill: "#006400",
angle: 90,
});
// Adding it to the canvas
canvas.add(rect);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>示例 2
使用颜色名称而不是 RGBA 值
我们也可以使用特定的颜色而不是使用 RGBA 值。在此示例中,selectionColor 属性已设置为颜色“红色”。
<!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>Setting the color of a selection area using FabricJs</h2>
<p>Select an area around the object to see the color of the selection area.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
selectionColor: "red",
});
// Creating an instance of the fabric.Rect class
var rect = new fabric.Rect({
left: 170,
top: 90,
width: 60,
height: 80,
fill: "#006400",
angle: 90,
});
// Adding it to the canvas
canvas.add(rect);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP