如何使用 FabricJS 矯正影像物件?


在本教程中,我們將學習如何使用 FabricJS 矯正影像物件。我們可以透過建立fabric.Image的例項來建立影像物件。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性輕鬆自定義它。為了矯正影像物件,我們使用straighten方法。

語法

straighten(): fabric.Object

在不使用straighten方法的情況下為angle屬性傳遞值

示例

讓我們看一個程式碼示例,看看當不使用straighten方法時我們的影像物件是什麼樣子。straighten方法透過將其從當前角度旋轉到 0、90、180 或 270 等來矯正物件,具體取決於哪個角度更接近。angle 屬性以度為單位設定物件的旋轉角度。在這裡,我們將角度指定為 45。但是,由於我們沒有應用straighten屬性,因此旋轉角度將保持為 45 度。

<!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 the angle property a value without using the straighten method </h2> <p>You can see that the Image object has an angle of 45 degrees</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, angle: 45, }); // Add it to the canvas canvas.add(image); </script> </body> </html>

使用straighten方法

示例

讓我們看一個程式碼示例,看看當將straighten方法與angle屬性結合使用時,影像物件是什麼樣子。雖然我們將旋轉角度設定為 45 度,但我們的影像物件將透過將其旋轉回 0 度來矯正,因為我們使用了straighten方法。

<!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 straighten method</h2> <p> You can see that the angle of rotation is 0 degree for the image object </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, angle: 45, }); // Add it to the canvas canvas.add(image); // Using the straighten method image.straighten(); </script> </body> </html>

更新於: 2022年10月28日

267 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.