如何使用 FabricJS 自定义画布的视口?
在本文中,我们将学习如何使用 FabricJS 自定义画布的视口。视口是用户在画布上可见的区域。我们可以使用 `viewportTransform` 属性来自定义视口,该属性允许我们控制视口的变换。
语法
new fabric.Canvas(element: HTMLElement|String, { viewportTransform: Array }: Object)参数
element − 此参数是<canvas> 元素本身,可以使用 Document.getElementById() 或<canvas> 元素的 ID 获取。FabricJS 画布将在此元素上初始化。
options (可选) − 此参数是一个对象,它为我们的画布提供额外的自定义选项。使用此参数,可以更改与画布相关的许多属性,例如颜色、光标、边框宽度等等,其中 `viewportTransform` 就是一个属性。它接受一个包含 6 个值的数组,这些值决定了平面上的变换。其默认值为 `canvas.viewportTransform = [1, 0, 0, 1, 0, 0]`。
示例 1
将 `viewportTransform` 属性作为键传递给类
让我们来看一个如何自定义画布视口的代码示例。在此示例中,我们使用了值 `[0.7, 0.1, 0.5, 0.9, 20, 50]`,分别表示scaleX、skewY、skewX、scaleY、translationX 和 translationY。
<!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>Customizing the viewport of the canvas using FabricJS </h2>
<p>Select an area around the object to see the viewports.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
viewportTransform: [0.7, 0.1, 0.5, 0.9, 20, 50]
});
// 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>示例 2
将 `viewportTransform` 属性作为键传递,并使用自定义值缩小对象
让我们来看另一个代码示例,我们将显示一个按 80% 缩放并向右下角平移(无倾斜)的变换。
<!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>Customizing the viewport of the canvas using FabricJS </h2>
<p>Select an area around the object to see the viewports.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas", {
viewportTransform: [0.8, 0, 0, 0.8, 50, 50]
});
// 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