FabricJS 设置圆形选择的背景颜色

fabricjsjavascripthtml5 canvas更新于 2025/2/4 12:28:17

在本教程中,我们将学习如何使用 FabricJS 设置圆形选择的背景颜色。圆形是 FabricJS 提供的各种形状之一。为了创建一个圆形,我们必须创建一个 fabric.Circle 类的实例并将其添加到画布中。当圆形被主动选中时,我们可以更改对象的尺寸、旋转它或对其进行操作。我们可以使用 selectionBackgroundColor 属性更改圆形选择的背景颜色。

语法

new fabric.Circle({ choiceBackgroundColor : String }: Object)

参数

  • 选项(可选) −此参数是一个 Object,可为我们的圆圈提供额外的自定义。使用此参数,可以更改与 selectionBackgroundColor 属性相关的属性(例如颜色、光标、笔触宽度和许多其他属性)。

选项键

  • selectionBackgroundColor − 此属性接受一个 String,该字符串确定选择的背景颜色。

示例 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>Setting the Background Colour on selection of circle</h2>
      <p>Select the object and notice the selection area. Here we have not used the <b>selectionBackgroundColor</b> property.</p>
      <canvas id="canvas"></canvas>
   
      <script>
         // 启动一个canvas实例
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle({
            left: 115,
            top: 50,
            radius: 50,
            fill: "#85bb65"
         });
         canvas.add(circle);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

示例 2

将selectionBackgroundColor属性作为键传递

在此示例中,我们为selectionBackgroundColor属性分配一个值。在本例中,我们已将"skyBlue"颜色传递给它,因此选择区域看起来是天蓝色。

<!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 Background Colour on selection of circle</h2>
      <p>Select the object to see the background color of the selection area. Here we have used the <b>selectionBackgroundColor</b> property and assigned it 'skyBlue' color. </p>
      <canvas id="canvas"></canvas>

      <script>
         // 启动一个canvas实例
         var canvas = new fabric.Canvas("canvas");
         var circle = new fabric.Circle({
            left: 115,
            top: 50,
            radius: 50,
            fill: "#85bb65",
            selectionBackgroundColor: "skyBlue"
         });
         canvas.add(circle);
         canvas.setWidth(document.body.scrollWidth);
         canvas.setHeight(250);
      </script>
   </body>
</html>

相关文章


有用资源