FabricJS – 如何設定影像選區的背景顏色?
在本教程中,我們將學習如何使用 FabricJS 設定影像選區的背景顏色。我們可以透過建立 fabric.Image 的例項來建立影像物件。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性輕鬆自定義它。為了設定影像的背景顏色,我們使用 selectionBackgroundColor 屬性。
語法
new fabric.Image( element: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String, { selectionBackgroundColor: String }: Object, callback: function)
引數
element − 此引數接受HTMLImageElement、HTMLCanvasElement、HTMLVideoElement 或 String,表示影像元素。字串應為 URL,並將載入為影像。
options (可選) − 此引數是一個物件,它為我們的物件提供額外的自定義。使用此引數,可以更改與影像物件相關的原點、筆劃寬度和許多其他屬性,其中selectionBackgroundColor 是一個屬性。
callback (可選) − 此引數是一個函式,在最終應用過濾器後將呼叫該函式。
選項鍵
selectionBackgroundColor − 此屬性接受字串值。分配的值將確定選區的背景顏色。
未使用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 select the image object to see that the selection area has no colour </p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.tw/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 50, }); // Add it to the canvas canvas.add(image); </script> </body> </html>
將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 select the image object to see that the selection area has a light cyan colour </p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.tw/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 50, selectionBackgroundColor: "#e0ffff", }); // Add it to the canvas canvas.add(image); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP