
在本文中,我们将学习如何使用 FabricJS 在画布上启用居中缩放。在 FabricJS 中,当从角落拖动对象时,对象会按比例变换。我们可以使用 centeredScaling 属性来使用中心作为变换的原点。
语法
new fabric.Canvas(element: HTMLElement|String, { centeredScaling: Boolean }: Object)参数
元素 - 此参数是
选项(可选) - 此参数是一个对象,它提供对我们的画布进行额外的定制。利用这个参数可以改变画布相关的颜色、光标、边框宽度等很多属性,其中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>










