如何使用 FabricJS 繪製虛線?
我們可以透過建立 fabric.Polyline 的例項來建立一個 Polyline 物件。Polyline 物件可以由一組連線的直線段來表徵。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。
我們可以使用 strokeDashArray 屬性來建立帶有 Polyline 的虛線。
語法
new fabric.Polyline(points: Array, { strokeDashArray: Array }: Object)
引數
points − 此引數接受一個陣列,表示構成 polyline 物件的點陣列。
options (可選) − 此引數是一個物件,它為我們的文字提供額外的自定義選項。使用此引數可以更改與物件的 strokeDashArray 屬性相關的顏色、游標、筆劃寬度以及許多其他屬性。
選項鍵
strokeDashArray − 此屬性接受一個陣列,透過陣列指定間隔來指定虛線圖案。例如,如果我們傳遞一個值為 [2,3] 的陣列,則表示 2px 的虛線和 3px 的間隙,並無限重複此圖案。
示例 1:建立 fabric.Polyline() 的例項並將其新增到我們的畫布
讓我們來看一個程式碼示例,說明我們如何首先將 polyline 物件新增到我們的畫布。唯一需要的引數是 points 陣列,而第二個引數是可選的 options 物件。
<!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>Creating an instance of fabric.Polyline() and adding it to our canvas </h2>
<p>You can see that the polyline object has been added</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating a points array
var points = [
{ x: 30, y: 500 },
{ x: 0, y: 0 },
{ x: 600, y: 0 },
];
// Initiating a polyline object
var polyline = new fabric.Polyline(points, {
left: 100,
top: 40,
fill: "white",
strokeWidth: 4,
stroke: "pink",
});
// Adding it to the canvas
canvas.add(polyline);
</script>
</body>
</html>
示例 2:使用 strokeDashArray 新增虛線圖案
正如我們在這個示例中看到的,我們將使用 strokeDashArray 屬性向我們的 Polyline 新增虛線。
<!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>Using the strokeDashArray to add the dotted pattern</h2>
<p>You can see that the polyline object has been added with dotted line</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating a points array
var points = [
{ x: 30, y: 500 },
{ x: 0, y: 0 },
{ x: 600, y: 0 },
];
// Initiating a polyline object with strokeDashArray
var polyline = new fabric.Polyline(points, {
left: 100,
top: 40,
fill: "white",
strokeWidth: 4,
stroke: "pink",
strokeDashArray: [7, 10],
});
// Adding it to the canvas
canvas.add(polyline);
</script>
</body>
</html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP