如何使用 Fabric.js 更改畫布文字的背景顏色?


fabric.Text 用於更改畫布文字的角樣式。Fabric.js 的 Text 類透過使用 fabric.Text 類提供文字抽象,允許我們以面向物件的方式處理文字。與 canvas 類相比,Text 類提供了更豐富的功能。

文字物件包含不同的屬性,但是更改畫布文字的背景顏色和渲染可以使用其中一個顏色屬性,即 textBackgroundColor 來完成。透過定義顏色屬性的值,我們可以更改背景顏色。

語法

以下是 fabric.Text 的語法:

fabric.Text( text: string, textBackgroundColor: string);

引數

  • text − 用於指定文字

  • textBackgroundColor − 指定背景顏色

示例 1

在這個示例中,我們需要使用 CDN (內容分發網路) 匯入 Fabric.js 庫。讓我們為 Fabric.js 庫提供的 Canvas 和 Text 初始化新的例項,它有助於使用 textBackgroundColor 屬性更改文字的背景顏色並在畫布上渲染文字。

<html>
   <head>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
   </head>
   <body>
      <h2>Changing the background color of a canvas type text</h2>
      <p> We change the background clor the canvas type text to "blue". </p>
      <canvas id="canvas" width="500" height="80""></canvas>
      <script>
         // Create the canvas for the new instance
         var canvas = new fabric.Canvas("canvas");

         // Create a new instance of a text class
         var content = new fabric.Text('Tutorialspoint', {
            textBackgroundColor: "blue"
         });

         // Rendering the content on Canvas
         canvas.add(content);
      </script>
   </body>
</html>

正如我們在示例中看到的,這裡我們使用 Fabric.js 的 Text 類透過使用 fabric.Text 物件來提供文字抽象。在這裡,我們使用 Text 的 textBackgroundColor 屬性將文字的背景顏色更改為藍色。

讓我們來看另一個示例,我們將學習如何為我們定義了背景顏色的畫布更改畫布文字的背景顏色。

示例 2

初始化 Canvas 和 Text 的新例項,它有助於使用 textBackgroundColor 屬性更改文字的背景顏色並在畫布上渲染文字。對於畫布,我們使用 Text 類的 backgroundColor 屬性定義背景顏色。

<html>
   <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
   </head>
   <body>
      <h2>Changing the background color of a canvas type text</h2>
      <p> The background color of canvas type text is changed to pink.</p>
      <canvas id="canvas" width="450" height="100";"></canvas>
      <script>
         // Creating the canvas for the new instance
         var canvas = new fabric.Canvas("canvas");

         // Creating a new instance of a text class
         var content1 = new fabric.Text('Welcome to Tutorials point', {
            textBackgroundColor: "pink"
         });
         
         // Creating a new instance of a canvas class
         var canvas = new fabric.Canvas('canvas', {
            backgroundColor: 'yellow'
         });
         
         // Rendering the content on canvas
         canvas.add(content1);
      </script>
   </body>
</html>

正如我們在示例中看到的,這裡我們使用 Fabric.js 的 text 類透過使用 fabric.Text 類來提供文字抽象。使用 Text 類的 textBackgroundColor 屬性,我們可以將文字的背景顏色更改為粉色。並透過使用 Text 類的 backgroundColor 屬性,我們將畫布的背景顏色更改為黃色。

我們討論瞭如何使用 Fabric.js 更改畫布文字的背景顏色。我們在這裡看到了兩個不同的示例,在第一個示例中,我們使用了 Text 類的 textBackgroundColor 屬性將文字的背景顏色更改為藍色。

在第二個示例中,我們使用了 Text 類及其屬性,如 backgroundColor 和 textBackgroundColor,來更改文字的背景顏色和畫布的背景顏色。

更新於:2023年2月21日

瀏覽量:589

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.