Fabric.js 图片 centeredRotation 属性
Fabric.js 是一个用于处理画布的 JavaScript 库。画布图片是 fabric.js 的一个类,用于创建图片实例。画布图片意味着图片可移动,并且可以根据需求进行拉伸。centeredRotation 属性用于沿着中心旋转画布图片,即原点。
方法: 首先导入 fabric.js 库。导入库之后,在 body 标签中创建一个包含图片的画布块。接下来,使用由 Fabric.JS 提供的 Canvas 和 Image 类初始化实例,并首先将 centeredRotation 属性设置为 false,然后设置为 true,并尝试使用控制器旋转图片。然后将图片实例渲染到画布上并将元素居中。
语法:
fabric.Image(image, {
centeredRotation:Boolean
});
参数: 上述函数有两个参数,如上述所提及,并在下面进行描述:
- image: 此参数接收图像。
- centeredRotation: 此参数定义是否启用或禁用画布图像的中心旋转。
示例 1: 此示例使用FabricJS来启用画布图像的中心旋转。图像的旋转是沿着原点进行的,如下面的示例所示。
<!DOCTYPE html>
<html>
<head>
<!-- Adding the FabricJS library -->
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">
</script>
</head>
<body>
<h1 style="color: green;">GeeksforGeeks</h1>
<b>Fabric.js | Image centeredRotation Property </b>
<canvas id="canvas" width="300" height="250"
style="border:2px solid #000000">
</canvas>
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png"
width="100" height="100" id="my-image">
<br>
<button onclick="func()">Clickme</button>
<script>
// Create the instance of canvas object
var canvas = new fabric.Canvas("canvas");
// Getting the image
var img= document.getElementById('my-image');
// Creating the image instance
var imgInstance = new fabric.Image(img, {
centeredRotation:true
});
// Rendering the image to canvas
canvas.add(imgInstance);
canvas.centerObject(imgInstance);
</script>
</body>
</html>
输出:
示例2:
<!DOCTYPE html>
<html>
<head>
<!-- Adding the FabricJS library -->
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">
</script>
</head>
<body>
<h1 style="color: green;">GeeksforGeeks</h1>
<b>Fabric.js | Image centeredRotation Property </b>
<canvas id="canvas" width="300" height="300"
style="border:2px solid #000000">
</canvas>
<img src =
"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png"
width="100" height="100" id="my-image"
style="display:none">
<br>
<button onclick="func()">Clickme</button>
<script>
// Create the instance of canvas object
var canvas = new fabric.Canvas("canvas");
// Getting the image
var img= document.getElementById('my-image');
// Creating the image instance
var imgInstance = new fabric.Image(img, {
centeredRotation:false
});
// Rendering the image to canvas
canvas.add(imgInstance);
func=()=>{
var imgInstance = new fabric.Image(img, {
centeredRotation:true
});
// Rendering the image to canvas
canvas.add(imgInstance);
canvas.clear();
canvas.add(imgInstance);
}
</script>
</body>
</html>
输出:

极客教程