如何在 FabricJS 中通过点击按钮随机生成 Polyline 对象?
Polyline 对象可以用一组连接的直线段来表示。由于它是 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松地自定义它。
我们将创建一个程序,按下按钮将随机生成一个 Polyline 对象并将其添加到我们的画布中。
语法
new fabric.Polyline(points: Array, options: Object)
参数
points − 此参数接受一个数组,表示构成 polyline 对象的点数组。
options (可选) − 此参数是一个对象,它为我们的对象提供额外的自定义选项。使用此参数可以更改与 Polyline 对象相关的原点、笔划宽度和许多其他属性。
示例 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: 50 },
{ x: 0, y: 0 },
{ x: 60, y: 0 },
];
// Initiating a polyline object
var polyline = new fabric.Polyline(points, {
left: 100,
top: 40,
fill: "white",
strokeWidth: 4,
stroke: "cyan",
});
// Adding it to the canvas
canvas.add(polyline);
</script>
</body>
</html>
示例 2:添加一个按钮以随机生成 Polyline 对象
让我们来看一个代码示例,说明如何随机生成 Polyline 对象。我们将添加一个按钮,按下该按钮将在画布上添加随机生成的 Polyline。我们将使用一个函数来随机生成 Polyline,在该函数中我们将使用Math.random()方法来生成随机点。
<!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>Adding a button to randomly generate the Polyline objects</h2>
<p> Click on the `Add Polyline!` Button to add a randomly generated polyline to the canvas </p>
<canvas id="canvas"></canvas>
<button type="button" onclick="addPolyline()">Add Polyline!</button>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a Polyline object
var polyLine = new fabric.Polyline([
{ x: 500, y: 200 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 100 },
{ x: 350, y: 600 },
], {
stroke: "cyan",
fill: "white",
strokeWidth: 5,
});
// Add it to the canvas instance
canvas.add(polyLine);
// Function to generate random Polyline and adding it to canvas
function addPolyline() {
var randomPolyLine = new fabric.Polyline([
{x: Math.random() * 500, y: Math.random() * 200},
{x: Math.random() * 500, y: Math.random() * 600},
{x: Math.random() * 300, y: Math.random() * 100}],
{
stroke: "cyan",
fill: "rgb(256,256,256,0)",
strokeWidth: 5,
});
canvas.add(randomPolyLine)
}
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP