如何在使用 FabricJS 的畫布上啟用居中縮放?
在本文中,我們將學習如何在使用 FabricJS 的畫布上啟用居中縮放。在 FabricJS 中,從角拖動物件時,物件會按比例變換。我們可以使用 `centeredScaling` 屬性以中心作為變換的原點。
語法
new fabric.Canvas(element: HTMLElement|String, { centeredScaling: Boolean }: Object)
引數
element − 此引數是<canvas> 元素本身,可以使用 `Document.getElementById()` 或<canvas> 元素本身的 ID 獲取。FabricJS 畫布將在此元素上初始化。
options (可選) − 此引數是一個物件,它為我們的畫布提供額外的自定義選項。使用此引數可以更改與畫布相關的顏色、游標、邊框寬度和許多其他屬性,其中 `centeredScaling` 是一個屬性。它接受一個布林值,該值決定物件是否應使用中心點作為變換的原點。其預設值為 False。
示例 1
將 `centeredScaling` 鍵的值設定為 false
讓我們來看一個程式碼示例,說明當 `centeredScaling` 設定為 False 時物件如何縮放。
<!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>Enabling centered scaling in canvas using FabricJS</h2> <p>Select the object and try to resize it by its corners. The object will scale non-uniformly from its center.</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas", { centeredScaling: false }); // Creating an instance of the fabric.Rect class var circle = new fabric.Circle({ left: 200, top: 100, radius: 40, fill: "blue", }); // Adding it to the canvas canvas.add(circle); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); </script> </body> </html>
示例 2
將 `centeredScaling` 鍵的值設定為 True
預設情況下,centeredScaling 鍵設定為 False。因此,我們需要將此鍵傳遞給類並將其值賦值為 true,才能使物件使用其中心作為變換的原點。
<!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>Enabling centered scaling in canvas using FabricJS</h2> <p>Here we have set <b>centeredScaling</b> to True. Select the object and try to resize it by its corners. The object will scale uniformly from its center. </p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas", { centeredScaling: true }); // Creating an instance of the fabric.Rect class var circle = new fabric.Circle({ left: 200, top: 100, radius: 40, fill: "blue", }); // Adding it to the canvas canvas.add(circle); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); </script> </body> </html>
廣告