如何使用 FabricJS 从顶部设置矩形的位置?
在本教程中,我们将使用 FabricJS 设置矩形的位置。top 属性允许我们操作对象的位置。默认情况下,顶部位置相对于对象顶部。
语法
new fabric.Rect({ top: Number }: Object)参数
选项(可选) - 此参数是一个对象,它为我们的矩形提供了额外的自定义功能。使用此参数,可以更改与对象的属性相关的属性,例如颜色、光标、笔触宽度以及许多其他属性,其中top 是一个属性。
选项键
top - 此属性接受一个数字,允许我们设置矩形的顶部位置。
示例 1
矩形对象的默认外观
让我们看一个代码示例,以了解当不使用 top 属性时,我们的矩形对象将如何显示。
<!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>Default appearance of the Rectangle object</h2>
<p>This is how our rectangle object appears when the top property is not used.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a rectangle object
var rect = new fabric.Rect({
left: 55,
width: 170,
height: 70,
fill: "black",
padding: 9,
stroke: "#483d8b",
strokeWidth: 5,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>示例 2
将 top 属性作为键传递,并带有自定义值
在此示例中,我们将 top 属性作为键传递,其值为 90。这意味着我们的矩形对象将放置在距顶部 90px 的位置。
<!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>Passing the top property as key with a custom value</h2>
<p>Now the rectangle is placed at a distance of 90px from the top</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a rectangle object
var rect = new fabric.Rect({
left: 55,
top: 90,
width: 170,
height: 70,
fill: "black",
padding: 9,
stroke: "#483d8b",
strokeWidth: 5,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP