在本文中,我们将学习如何使用 fabricjs 在画布上启用居中缩放。在 fabricjs 中,当从角落拖动对象时,对象会按比例变换。我们可以使用 centeredscaling 属性来使用中心作为变换的原点。
语法new fabric.canvas(element: htmlelement|string, { centeredscaling: boolean }: object)
参数元素 - 此参数是 元素本身,可以使用 document.getelementbyid() 或 元素本身的 id 派生。 fabricjs 画布将在此元素上初始化。
选项(可选) - 此参数是一个对象,它提供对我们的画布进行额外的定制。利用这个参数可以改变画布相关的颜色、光标、边框宽度等很多属性,其中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 键为设置为假。因此,我们需要将key传递给类,并赋予它一个真实的值,以使对象能够以它们的中心作为变换的原点。
<!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>
以上就是如何使用 fabricjs 在画布上启用居中缩放?的详细内容。