如何使用 FabricJS 设置椭圆的不透明度?

在本教程中,我们将学习如何使用 FabricJS 设置椭圆的不透明度。椭圆形是 FabricJS 提供的各种形状之一。为了创建一个椭圆,我们必须创建一个 Fabric.Ellipse 类的实例并将其添加到画布中。我们可以通过添加填充颜色来自定义椭圆对象,消除其边框,甚至更改其尺寸。同样,我们也可以使用 opacity 属性来更改其不透明度。
语法
new fabric.Ellipse({ opacity: Number }: Object)参数
选项(可选)- 此参数是一个对象< /em> 为我们的椭圆提供额外的定制。使用此参数,可以更改与不透明度为属性的对象相关的颜色、光标、边框宽度和许多其他属性。
选项键
不透明度 - 此属性接受数字强> 允许我们控制对象的不透明度。 opacity 属性的默认值为 1。
示例 1
椭圆对象的默认外观< /strong>
让我们看一段代码,看看我们的椭圆对象在 opacity 属性的默认值下是什么样子。在此示例中,我们不会将任何不透明键传递给类,如下所示 -
<!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>How to set the opacity of Ellipse using FabricJS?</h2>
<p>Observe that here we have not used the <b>opacity</b> property, so by default, it takes the value 1. </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
// Initiate an ellipse instance
var ellipse = new fabric.Ellipse({
left: 115,
top: 50,
rx: 80,
ry: 50,
fill: "#ff1493",
});
// Adding it to the canvas
canvas.add(ellipse);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>示例 2
将 opacity 属性作为键传递
在此示例中,我们将了解如何分配值opacity 属性更改画布中椭圆对象的不透明度。这里我们使用 0.3 作为不透明度,从而使我们的椭圆对象看起来半透明而不是完全不透明。
<!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>How to set the opacity of Ellipse using FabricJS?</h2>
<p>Here we have set the <b>opacity</b> at 0.3, which is why the ellipse is less opaque.</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
// Initiate an ellipse instance
var ellipse = new fabric.Ellipse({
left: 115,
top: 50,
rx: 80,
ry: 50,
fill: "#ff1493",
opacity: 0.3,
});
// Adding it to the canvas
canvas.add(ellipse);
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
</script>
</body>
</html>
javascript