如何使用 FabricJS 创建带有圆形的画布?
在本教程中,我们将学习如何使用 FabricJS 创建带有圆形对象的画布。圆形是 FabricJS 提供的各种形状之一。为了创建圆形,我们需要创建一个 fabric.Circle 类的实例并将其添加到画布中。
语法
new fabric.Circle({ radius: Number }: Object)参数
options (可选) − 此参数是一个 对象,它为我们的对象提供额外的自定义。使用此参数,可以更改与圆形相关的属性,例如颜色、光标、笔触宽度以及许多其他属性,其中 **半径** 是一个属性。
选项键
radius − 此属性接受一个 数字,用于确定圆形的半径。如果我们没有指定半径,我们的圆形将不会显示在画布上。
示例 1
创建 fabric.Circle() 的实例并将其添加到我们的画布中
让我们看一个如何将圆形添加到画布的示例。在这里,我们创建了一个半径为 50px 的圆形。stroke 属性表示边框颜色,strokeWidth 指定边框宽度。我们使用天蓝色填充对象,其十六进制值为 #80daeb。
<!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 a canvas with circle using FabricJS</h2>
<p>Here we have created a circle of radius 50px over a canvas. In addition, we have used the <b>fill</b> and <b>stroke</b> properties to color its body and outline. </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
// Creating an instance of the fabric.Circle class
var circle = new fabric.Circle({
left: 215,
top: 100,
radius: 50,
fill: "#80daeb",
stroke: "#00b7eb",
strokeWidth: 2,
});
// Adding it to the canvas
canvas.add(circle);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>示例 2
使用 set 方法操作圆形对象
在此示例中,我们使用 set 方法为圆形分配了属性,该方法是值的 setter。可以使用此方法更改与笔触、笔触宽度、半径、缩放、旋转等相关的任何属性。
<!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 a canvas with circle using FabricJS</h2>
<p>Here we have used the <b>set</b> method to create a circle of radius 40px and then filled the object with a color. </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
var circle = new fabric.Circle();
canvas.add(circle);
// Use set to set the properties
circle.set("radius", 40);
circle.set("fill", "green");
circle.set({
stroke: "rgba(133, 187, 101, 0.7)",
strokeWidth: 4
});
circle.set("left", 50);
circle.set("top", 50);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP