如何在FabricJS中设置自定义按键来启用/禁用画布的均匀缩放?
本文将学习如何在FabricJS中设置自定义按键来启用/禁用均匀缩放。在FabricJS中,从对象的角拖动时,对象会按比例变换。这称为均匀缩放。但是,我们可以使用uniScaleKey属性来启用/禁用此行为。
语法
new fabric.Canvas(element: HTMLElement|String, { uniScaleKey: String }: Object)参数
element − 此参数是<canvas> 元素本身,可以使用Document.getElementById()或<canvas> 元素的ID来获取。FabricJS画布将在此元素上初始化。
options (可选) − 此参数是一个对象,它为我们的画布提供额外的自定义选项。使用此参数,可以更改画布相关的许多属性,例如颜色、光标、边框宽度以及uniScaleKey属性。它接受一个字符串值,用于确定哪个键切换均匀缩放。其默认值为shiftKey。
示例1
将uniScaleKey属性的值设置为'altKey'
让我们看一个使用自定义按键在FabricJS中禁用均匀缩放的代码示例。在这里,我们将uniScaleKey设置为'altKey'。
<!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>Setting a custom key to enable/disable uniform scaling on a canvas</h2>
<p>Hold the <b>alt</b> key and stretch the object diagonally. The object will scale non-uniformly. </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
uniformScaling: true,
uniScaleKey: "altKey"
});
// Creating an instance of the fabric.Rect class
var circle = new fabric.Circle({
left: 215,
top: 100,
radius: 50,
fill: "orange",
});
// Adding it to the canvas
canvas.add(circle);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>示例2
将uniScaleKey属性的值设置为'ctrlKey'
我们也可以将'ctrlKey'作为uniScaleKey属性的值,因为它也是一个修饰键。如果uniScaleKey赋值为NULL或非修饰键,则其功能将被禁用。
在这个例子中,uniformScaling被设置为false,这意味着该功能被禁用。一旦我们按下ctrlKey,均匀缩放将再次启用。
<!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>Setting a custom key to enable/disable uniform scaling on a canvas </h2>
<p>Hold the <b>ctrl</b> key and stretch the object diagonally. It will scale uniformly. </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
uniformScaling: false,
uniScaleKey: "ctrlKey"
});
// Creating an instance of the fabric.Rect class
var circle = new fabric.Circle({
left: 215,
top: 100,
radius: 50,
fill: "red",
});
// Adding it to the canvas
canvas.add(circle);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP