如何使用 FabricJS 为三角形添加虚线描边?
在本教程中,我们将学习如何使用 FabricJS 为三角形添加虚线描边。三角形是 FabricJS 提供的各种形状之一。为了创建三角形,我们将必须创建一个`fabric.Triangle`类的实例并将其添加到画布中。`strokeDashArray`属性允许我们为对象的描边指定虚线图案。
语法
new fabric.Triangle( { strokeDashArray: Array }: Object)参数
options (可选) − 此参数是一个对象,它为我们的三角形提供了额外的自定义选项。使用此参数,可以更改与对象相关的属性,例如颜色、光标、描边宽度以及许多其他属性,其中`strokeDashArray`就是一个属性。
选项键
strokeDashArray − 此属性接受一个数组,允许我们为对象的描边指定虚线图案。例如,如果我们传入一个值为[2,3]的数组,则表示2像素的线段和3像素的间隙,并无限重复此图案。
示例 1
对象的描边默认外观
让我们来看一个代码示例,它描述了三角形对象的描边默认外观。由于我们没有使用`strokeDashArray`属性,因此没有显示任何虚线图案。
<!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 an object's stroke</h2>
<p>You can see there is no dash pattern in the stroke</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 triangle object
var triangle = new fabric.Triangle({
left: 150,
top: 30,
width: 90,
height: 80,
fill: "#b0e0e6",
stroke: "#5f9ea0",
strokeWidth: 7,
});
// Add it to the canvas
canvas.add(triangle);
</script>
</body>
</html>示例 2
将strokeDashArray属性作为键传递
在这个例子中,我们将`strokeDashArray`属性的值设置为[9,2]。这意味着将创建一个虚线图案,其中包含一条9像素长的线段,然后是一个2像素的间隙,然后再次绘制一条9像素长的线段,依此类推。
<!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 strokeDashArray property as key</h2>
<p>You can see there is a dash pattern in the stroke now</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 triangle object
var triangle = new fabric.Triangle({
left: 150,
top: 30,
width: 90,
height: 80,
fill: "#b0e0e6",
stroke: "#5f9ea0",
strokeWidth: 7,
strokeDashArray: [9, 2],
});
// Add it to the canvas
canvas.add(triangle);
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP