如何使用 FabricJS 沿 X 軸裁剪影像?


在本教程中,我們將學習如何使用 FabricJS 沿 X 軸裁剪影像。我們可以透過建立fabric.Image的例項來建立一個影像物件。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。為了沿 X 軸裁剪影像,我們使用cropX屬性。

語法

new fabric.Image( element: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String, { cropX: Number }: Object, callback: function)

引數

  • element − 此引數接受HTMLImageElement、HTMLCanvasElement、HTMLVideoElement 或 String,表示影像元素。字串應為 URL,並將作為影像載入。

  • options (可選) − 此引數是一個Object,它為我們的物件提供額外的自定義選項。使用此引數,可以更改與影像物件相關的許多屬性,其中cropX就是一個屬性,例如原點、描邊寬度等。

  • callback (可選) − 此引數是一個function,在應用最終過濾器後將被呼叫。

選項鍵

  • cropX − 此屬性接受一個Number值,表示沿 X 軸從原始影像大小裁剪的畫素數。

影像物件的預設外觀

示例

讓我們來看一個程式碼示例,說明在不使用cropX屬性時影像物件的外觀。正如我們所看到的,沿 X 軸沒有影像裁剪。

<!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 appearance of Image object</h2> <p>You can see that there is no image crop along the x-axis</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: 110, }); // Add it to the canvas canvas.add(image); </script> </body> </html>

使用cropX屬性

示例

在此示例中,我們使用了cropX屬性併為其賦值 25。因此,影像沿 X 軸裁剪了 25 畫素。

<!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>Using the cropX property</h2> <p>You can see that there is a 25px image crop along the x-axis</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: 110, cropX: 25, }); // Add it to the canvas canvas.add(image); </script> </body> </html>

結論

在本教程中,我們使用兩個示例演示瞭如何使用 FabricJS 沿 X 軸裁剪影像。

更新於:2022年10月26日

2K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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